Android編程之圖片相關代碼集錦_Android

來源:互聯網
上載者:User

本文執行個體總結了Android編程之圖片相關代碼。分享給大家供大家參考,具體如下:

1. 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; } 

2.字串轉化為Bitmap:

/** * @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; } 

3.Bitmap轉化為Drawable:

/** * @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數群組轉換Drawble對象:

/**  * @param bytes byte數組  * @return drawble對象  */ public static Drawable byteArrayToDrawable(byte[] bytes) {  return null == bytes ? null : bitmapToDrawable(BitmapFactory.decodeByteArray(bytes, 0, bytes.length)); } 

4.Drawable轉化為bitmap:

/** * Drawble對象轉Bitmap對象 * @param drawable drawble對象 * @return bitmap對象 */ public static Bitmap drawableToBitmap(Drawable drawable) {   return null == drawable ? null : ((BitmapDrawable) drawable).getBitmap(); } 

5.byte數群組轉換Bitmap對象:

/** * @param bytes byte數組 * @return bitmap對象 */ public static Bitmap byteArrayToBitmap(byte[] bytes) {   return null == bytes ? null : BitmapFactory.decodeByteArray(bytes, 0, bytes.length); } 

6.圖片去色,返回灰階圖片(老式圖片):

/** * @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; } 

7.對圖片進行縮放:

/** * @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; } 

8.獲得圖片的倒影,同時倒影漸層效果:

/** * @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); } 

9.儲存圖片到SDCard:

/** * @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();    }   } }

10.從SDCard中擷取圖片:

/** * @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; }

11.圖片壓縮處理:

/** * 對圖片進行壓縮,主要是為瞭解決控制項顯示過大圖片佔用記憶體造成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); }

12. 擷取可用記憶體的最大值(App使用記憶體超出這個值會引起OutOfMemory異常):

private int getMaxMemoryForApp() {   int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);   return maxMemory; }

13.將圖片裁剪成圓圈:

/** * 將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程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.