Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 圖像資料轉換的各種方法彙整

編輯:關於 Android 程式設計

在 Android 中處理圖像是再常見不過的任務,這裡彙整一些實際用過、相當實用的圖片資料轉換方法,方便日後查閱。

轉為 Bitmap

由 RGB 字串轉 Bitmap

private Bitmap createColorBitmap(String rgb, int width, int height) {
      Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
      int color = Color.parseColor(rgb);
      bmp.eraseColor(color);
      return bmp;
}
//Usage
Bitmap bmp = createColorBitmap("#cce8cf", 200, 50);

由 Color 值轉 Bitmap

private Bitmap createColorBitmap(int color, int width, int height) {
  Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
  bmp.eraseColor(color);
  return bmp;
}
//Usage
Bitmap bmp = createColorBitmap(Color.BLUE, 200, 50);

由位元組陣列轉 Bitmap

private Bitmap getBitmapFromByteArray(byte[] array) {
  return BitmapFactory.decodeByteArray(array, 0, array.length);
}

由檔案轉 Bitmap

private Bitmap getBitmapFromFile(String pathName) {
      return BitmapFactory.decodeFile(pathName);
}

由資源轉 Bitmap

private Bitmap getBitmapFromResource(Resources res, int resId) {
      return BitmapFactory.decodeResource(res, resId);
  }

由串流轉 Bitmap

private Bitmap getBitmapFromStream(InputStream inputStream) {
      return BitmapFactory.decodeStream(inputStream);
}

由 Drawable 轉 Bitmap

Bitmap icon = BitmapFactory.decodeResource(context.getResources(),R.drawable.icon_resource);

轉為 Drawable

由資源轉 Drawable

Drawable drawable = getResources().getDrawable(R.drawable.ic_launcher);

由 Bitmap 轉 Drawable

Drawable d = new BitmapDrawable(getResources(),bitmap);

圖片圓角呈現

只要對 Bitmap 稍作處理即可,其中 pixels 代表邊角圓角半徑:

public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = pixels;
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }

這些方法涵蓋了日常開發中常見的圖片型別轉換與圓角處理,收錄起來以備不時之需。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved