package com.test.yyoung.transferBitmap;
import android.util.Log;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import com.google.protobuf.ByteString;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import static android.graphics.Bitmap.*;
public class TypeConvertTool {
private final static String TAG = "grpc_TypeConvertTool";
//Drawable -> Bitmap
public static Bitmap getBitmapIcon(Drawable drawable) {
//BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
//return bitmapDrawable.getBitmap();
Bitmap bmp = createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
Log.i(TAG, "getBitmapIcon");
return bmp;
}
//Drawable -> byte[]
public static byte[] getByteArrayIcon(Drawable drawable) {
if (drawable != null) {
Bitmap bitmap = getBitmapIcon(drawable);
if (bitmap != null) {
//ByteArrayOutputStream bytes = new ByteArrayOutputStream();
//bitmap.compress(CompressFormat.PNG, 100, bytes);
//return bytes.toByteArray();
int byteCounts = bitmap.getByteCount();
ByteBuffer byteBuffer = ByteBuffer.allocate(byteCounts);
bitmap.copyPixelsToBuffer(byteBuffer);
return byteBuffer.array();
}
}
return null;
}
//grpc ByteString -> byte[]
public static byte[] byteStringToBytes(ByteString bs) {
int len = bs.size();
if (len <= 0) {
Log.e(TAG, "input ByteString cannot be empty.");
return null;
}
byte[] bytes = new byte[len];
bs.copyTo(bytes, 0);
return bytes;
}
//byte[] -> Bitmap
public static Bitmap bytesToBitmap(byte[] bytes, int width, int height) {
if (bytes.length <= 0 || width <= 0 || height <= 0) {
Log.e(TAG, "input byte[] bytes or width or height cannot be <= 0.");
return null;
}
Bitmap bmp = Bitmap.createBitmap(width, height, Config.ARGB_8888);
try {
//bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
//byteBuffer.rewind();
byteBuffer.position(0);
bmp.copyPixelsFromBuffer(byteBuffer);
} catch (Exception e) {
e.printStackTrace();
}
return bmp;
}
//Bitmap -> Drawable
public static Drawable bitmapToDrawable(Bitmap bitmap) {
//NOTE: this funcion has been deprecated
return new BitmapDrawable(bitmap);
}
//ByteString -> Drawable
public static Drawable byteStringToDrawable(ByteString bs, int width, int height) {
//byte[] bytes = byteStringToBytes(bs);
byte[] bytes = bs.toByteArray();
Bitmap bitmap = bytesToBitmap(bytes, width, height);
return bitmapToDrawable(bitmap);
}
}