Various methods of Android for image data conversion

  • 2020-06-12 10:36:12
  • OfStack

Image processing is a very common thing in Android, so here are some hands-on methods for processing image data.

To Bitmap

Turn Bitmap RGB value


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);

Turn Bitmap Color value


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);

Byte array to Bitmap


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

Read file to Bitmap


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

Read resource to Bitmap


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

Input flow Bitmap


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

Turn Drawable Bitmap


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

To Drawable

Resource over Drawable


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

Turn Bitmap Drawable

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

The picture is shown with rounded corners

The image data bitmap can be processed, where pixels is the radius of the corner.


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


Related articles: