編輯:Android 開發實例
本文整理了一系列 Android 圖片處理的常用程式碼,涵蓋格式轉換、縮放、倒影、圓角、壓縮等常見操作,非常適合收藏起來當作工具庫隨時查用。
/** * @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; } /** * @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)); } /** * Drawble對象轉Bitmap對象 * @param drawable drawble對象 * @return bitmap對象 */ public static Bitmap drawableToBitmap(Drawable drawable) { return null == drawable ? null : ((BitmapDrawable) drawable).getBitmap(); } /** * @param bytes byte數組 * @return bitmap對象 */ public static Bitmap byteArrayToBitmap(byte[] bytes) { return null == bytes ? null : BitmapFactory.decodeByteArray(bytes, 0, bytes.length); } /** * @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; } /** * @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; } /** * @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); } /** * @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; } /** * 對圖片進行壓縮,主要是為了解決控件顯示過大圖片占用內存造成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); } private int getMaxMemoryForApp() { int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); return maxMemory; } /** * 將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 模擬器安裝 APK 的完整流程
若想在電腦上執行 Android 應用,可以透過 Android SDK 提供的模擬器與 adb 工具完成安裝。整個流程可拆為環境設定、啟動模擬器、執行安裝三個步驟。設定
Android 編譯與運行過程深入分析
Android 應用從原始碼到 APK 的過程,包含資源編譯、Java 編譯、dex 轉換、打包與簽名等步驟。理解這些流程有助於排查建置問題。 資源與 R 檔案 aap
Android 登入頁面教學:帳密驗證與剩餘次數提示
登入頁是許多 App 的第一道門。它向使用者索取一組憑證,換取進入的權限——不論是社群平台、雲端硬碟還是公司内部系统,邏輯都相同。 本章要動手做一個登入介面,並一併處理實
Android 自訂輸入法 IME 開發教程
輸入法編輯器,又稱 IME,是 Android 中讓使用者輸入文字的元件。開發者可自訂軟鍵盤、語音輸入或其他輸入方式,並讓使用者在系統設定中選擇。 基本架構 自訂 IM