編輯:關於 Android 程式設計
在 Android 開發裡,圖片的加載、轉換、壓縮與著色幾乎是每個項目都會遇到的環節。本文把日常開發中最常反覆使用的圖片操作整理成一份可直接複用的工具方法清單,涵蓋 Bitmap 與字符串、Drawable、byte 數組之間的相互轉換,以及灰度化、縮放、倒影、圓形裁剪、本地存取等常見場景,供大家查閱參考。
需要把圖片存進數據庫或通过网络傳輸時,通常會先將 Bitmap 壓縮成 PNG 字節流,再做 Base64 編碼轉為字符串;反向操作則是先解碼,再還原成 Bitmap。
/** * @param 位圖 * @return 轉化成的字符串 */ public static String bitmapToString(Bitmap bitmap) { // 將Bitmap轉換成字符串 String string = null; ByteArrayOutputStream bStream = new ByteArrayOutputStream(); bitmap.compress(CompressFormat.PNG, 100, bStream); byte[] bytes = bStream.toByteArray(); string = Base64.encodeToString(bytes, Base64.DEFAULT); return string; }
/** * @param string 字符串 * @return 轉化成的位圖 */ public static Bitmap stringToBitmap(String string) { // 將字符串轉換成Bitmap類型 Bitmap bitmap = null; try { byte[] bitmapArray; bitmapArray = Base64.decode(string, Base64.DEFAULT); bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length); } catch (Exception e) { e.printStackTrace(); } return bitmap; }
Drawable 是 Android 用於描述圖形資源的抽象概念,而 Bitmap 則是具體的位圖數據。下面幾個方法演示了兩者之間,以及從資源 ID、byte 數組出發的多種轉換方式。
/** * @param bitmap Bitmap位圖圖像 * @return Drawable 轉換後的Drawable對象 */ public static Drawable bitmapToDrawable(Bitmap bitmap) { if (bitmap == null) return null; if (160 != bitmap.getDensity()) { bitmap.setDensity(160); } return new BitmapDrawable(bitmap); }
根據圖片資源 ID 獲取 Drawable 對象:
/** * @param context 上下文 * @param id 圖片的資源ID * @return Drawable對象 */ public static Drawable resourceToDrawable(Context context,int id) { return null == context ? null : bitmapToDrawable(BitmapFactory.decodeResource(context.getResources(), id)); }
byte 數組轉換 Drawable 對象:
/** * @param bytes byte數組 * @return drawble對象 */ public static Drawable byteArrayToDrawable(byte[] bytes) { return null == bytes ? null : bitmapToDrawable(BitmapFactory.decodeByteArray(bytes, 0, bytes.length)); }
Drawable 轉 Bitmap:
/** * Drawble對象轉Bitmap對象 * @param drawable drawble對象 * @return bitmap對象 */ public static Bitmap drawableToBitmap(Drawable drawable) { return null == drawable ? null : ((BitmapDrawable) drawable).getBitmap(); }
byte 數組轉 Bitmap:
/** * @param bytes byte數組 * @return bitmap對象 */ public static Bitmap byteArrayToBitmap(byte[] bytes) { return null == bytes ? null : BitmapFactory.decodeByteArray(bytes, 0, bytes.length); }
通過 ColorMatrix 將飽和度設為 0,即可把彩色圖片轉為黑白的老照片風格。
/** * @param bitmap 傳入的bitmap * @return 去色後的圖片Bitmap對象 */ public static Bitmap toGrayscale(Bitmap bitmap) { int width,height; height = bitmap.getHeight(); width = bitmap.getWidth(); Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); Canvas c = new Canvas(bmpGrayscale); Paint paint = new Paint(); ColorMatrix cm = new ColorMatrix(); cm.setSaturation(0); ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm); paint.setColorFilter(f); c.drawBitmap(bitmap, 0, 0, paint); return bmpGrayscale; }
加載大圖前,先用 inJustDecodeBounds 讀取原始寬高而不佔用內存,再計算合適的採樣率,可有效避免 OOM。
/** * @param url 圖片的路徑 * @param requireSize 縮放的尺寸 * @return 縮放後的圖片Bitmap對象 */ public static Bitmap getScaleImage(String url,int requireSize) { BitmapFactory.Options o = new BitmapFactory.Options(); // 此屬性表示圖片不加載到內存,只是讀取圖片的屬性,包括圖片的高寬 o.inJustDecodeBounds = true; BitmapFactory.decodeFile(url, o); int width_tmp = o.outWidth,height_tmp = o.outHeight; int scale = 1; while (true) { if (width_tmp / 2 < requireSize || height_tmp / 2 < requireSize) break; width_tmp /= 2; height_tmp /= 2; scale *= 2; } BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; Bitmap bmp = BitmapFactory.decodeFile(url, o2); return bmp; }
通過逐行反轉像素並遞增 alpha 值,可以製作出一種自帶漸隱的倒影。
/** * @param bitmap 圖片源 * @return 處理後的圖片Bitmap對象 */ public static Bitmap createMirro(Bitmap bitmap) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); int shadow_height = 15; int[] pixels = new int[width * height]; bitmap.getPixels(pixels, 0, width, 0, 0, width, height); // shadow effect int alpha = 0x00000000; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int index = y * width + x; int r = (pixels[index] >> 16) & 0xff; int g = (pixels[index] >> 8) & 0xff; int b = pixels[index] & 0xff; pixels[index] = alpha | (r << 16) | (g << 8) | b; } if (y >= (height - shadow_height)) { alpha = alpha + 0x1F000000; } } // invert effect Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); for (int y = 0; y < height; y++) { bm.setPixels(pixels, y * width, width, 0, height - y - 1, width, 1); } return Bitmap.createBitmap(bm, 0, 0, width, shadow_height); }
把 Bitmap 寫入 SD 卡時,記得先確保父目錄存在;讀取時則順便更新文件的最近修改時間。
/** * @param imagePath 圖片保存路徑 * @param bm 被保存的bitmap對象 */ public static void saveImgToLocal(String imagePath, Bitmap bm) { if (bm == null || imagePath == null || "".equals(imagePath)) { return; } File f = new File(imagePath); if (f.exists()) { return; } else { try { File parentFile = f.getParentFile(); if (!parentFile.exists()) { parentFile.mkdirs(); } f.createNewFile(); FileOutputStream fos; fos = new FileOutputStream(f); bm.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.close(); } catch (FileNotFoundException e) { f.delete(); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); f.delete(); } } }
/** * @param imagePath 圖片在SDCard中保存的路徑 * @return 返回保存的bitmap對象 */ public static Bitmap getImageFromLocal(String imagePath) { File file = new File(imagePath); if (file.exists()) { Bitmap bitmap = BitmapFactory.decodeFile(imagePath); file.setLastModified(System.currentTimeMillis()); return bitmap; } return null; }
核心思路同樣是兩次解析:先讀取邊界獲取原始尺寸,再按目標寬高計算 inSampleSize,讓最終加載的圖片與展示控件大小相近,从而降低內存佔用。
/** * 對圖片進行壓縮,主要是為了解決控件顯示過大圖片占用內存造成OOM問題。 * 一般壓縮後的圖片大小應該和用來展示它的控件大小相近。 * @param context 上下文 * @param resId 圖片資源Id * @param reqWidth 期望壓縮的寬度 * @param reqHeight 期望壓縮的高度 * @return 壓縮後的圖片 */ public static Bitmap compressBitmapFromResourse(Context context, int resId, int reqWidth, int reqHeight) { final BitmapFactory.Options options = new BitmapFactory.Options(); /* * 第一次解析時,inJustDecodeBounds設置為true, * 禁止為bitmap分配內存,雖然bitmap返回值為空,但可以獲取圖片大小 */ options.inJustDecodeBounds = true; BitmapFactory.decodeResource(context.getResources(), resId, options); final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } options.inSampleSize = inSampleSize; //使用計算得到的inSampleSize值再次解析圖片 options.inJustDecodeBounds = false; return BitmapFactory.decodeResource(context.getResources(), resId, options); }
超出這個值就會引發 OutOfMemoryError,因此提前瞭解上限有助於做好內存規劃。
private int getMaxMemoryForApp() { int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); return maxMemory; }
借助 Canvas、抗鋸齒畫筆與 PorterDuff 的 SRC_IN 混合模式,可以把任意 Bitmap 裁剪成正圓形。
/** * 將Bitmap處理為圓形的圖片 * @param bitmap 處理之前的位圖 * @return 處理之後的位圖 */ public static Bitmap circlePic(Bitmap bitmap){ int width = bitmap.getWidth(); int height = bitmap.getHeight(); int r = width < height ? width/2:height/2;//圓的半徑,取寬和高中較小的,以便於顯示沒有空白 Bitmap outBitmap = Bitmap.createBitmap(r*2, r*2, Bitmap.Config.ARGB_8888);//創建一個剛好2r大小的Bitmap Canvas canvas = new Canvas(outBitmap); final int color =0xff424242; final Paint paint = new Paint(); /** * 截取圖像的中心的一個正方形,用於在原圖中截取 * 坐標如下: * 1.如果 w < h , 左上坐標(0, (h-w)/2) , 右上坐標(w, (h+w)/2) 偏移10 * 2.如果 w > h , 左上坐標((w-h)/2, 0) , 右上坐標((w+h)/2, h) 偏移10 */ final Rect rect = new Rect( width < height ? 0 : (width-height)/2, width < height ? (height-width)/2 - 10 : -10, width < height ? width : (width+height)/2, (width < height ? (height+width)/2 - 10: height - 10)); //創建一個直徑大小的正方形,用於設置canvas的顯示與設置畫布截取 final Rect rect2 = new Rect( 0, 0, r*2, r*2); //提高精度,用於消除鋸齒 final RectF rectF = new RectF(rect2); //下面是設置畫筆和canvas paint.setAntiAlias(true); canvas.drawARGB(0,0,0,0); paint.setColor(color); //設置圓角,半徑都為r,大小為rect2 canvas.drawRoundRect(rectF, r, r, paint); //設置圖像重疊時的顯示方式 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); //繪制圖像到canvas canvas.drawBitmap(bitmap, rect, rect2, paint); return outBitmap; }
以上就是這份圖片處理代碼集錦的全部內容,涵蓋了開發中絕大多數常見的圖片操作場景,希望能對大家的 Android 開發有所幫助。
Android Studio 1.4 的七個實用新特性盤點
前段時間把 Android Studio 更新到了 1.4,當時沒太在意。今天翻了一遍官方更新日誌,發現這個版本其實加了不少真能提升效率的功能,值得分享一下。 清單如下:
Android 打造旋轉木馬風格的音樂播放效果
一、靈感來源:百度在線音樂的旋轉木馬效果 就是畫面上這個效果——當音樂播放時,那張光碟輪子會像旋轉木馬一般不停轉動,看起來相當有趣。剛好想起前陣子做過音樂播放器,於是一
Android 自訂 View(一):打造可自動定位的橫向滾動選單
前言 已經好一陣子沒更新部落格了,今天帶來一個橫向滾動的選單,用的是 HorizontalScrollView。由於 HorizontalScrollView 滾動時無法
Android 實戰:手把手畫出圓形水波紋 LoadingView
本文一步步示範如何畫一個圓形水波紋的 loading 檢視。這類效果應用場景很多,例如顯示記憶體佔用百分比、下載進度等。 先備知識 貝塞爾曲線:用來畫出平滑的水波曲線