Android — View如何轉存成Bitmap或是ARGB byte array raw file

JLin
5 min readSep 14, 2021

--

如果你有需求將你畫面上的任何一個view轉成Bitmap,可以透過

public static Bitmap loadBitmapFromView(View v) {
if(v == null){
return null;
}

int h = v.getHeight();
int w = v.getWidth();

if(w <= 0 || h <= 0){
return null;
}

Bitmap b = Bitmap.createBitmap( w, h, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
v.draw(c);
return b;
}

如果用kotlin可以改為extension function

private fun View.saveToBitmap(): Bitmap? {
val h = height
val w = width
if (w <= 0 || h <= 0) {
return null
}
return Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888).apply {
val canvas = Canvas(this)
layout(left, top, right, bottom)
draw(canvas)
}
}

接著如果你想要存下他的ByteArray資料

可以透過

private static void saveBitmapToFile(Context context,Bitmap bitmap){
try {
File filePath = new File(path,"test.jpg");
if(filePath.exists()){
return;
}
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
int size = bitmap.getRowBytes() * bitmap.getHeight();
ByteBuffer byteBuffer = ByteBuffer.allocate(size);
bitmap.copyPixelsToBuffer(byteBuffer);
bos.write(byteBuffer.array());
bos.flush();
bos.close();
fileOutputStream.close();
} catch (FileNotFoundException e) {
//Log.w("TAG", "Error saving image file: " + e.getMessage());
} catch (IOException e) {
//Log.w("TAG", "Error saving image file: " + e.getMessage());
}
}

或是你要存 jpeg or png 可以使用

private static void saveBitmapToFile(Context context,Bitmap bitmap){
try {
File filePath = new File(path,"test.jpg");
if(filePath.exists()){
return;
}
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
bitmap.compress(Bitmap.CompressFormat.JPEG,90,fileOutputStream);
bos.flush();
bos.close();
fileOutputStream.close();
} catch (FileNotFoundException e) {
//Log.w("TAG", "Error saving image file: " + e.getMessage());
} catch (IOException e) {
//Log.w("TAG", "Error saving image file: " + e.getMessage());
}
}

或是你單純要拿Bitmap的rawByteArray,透過kotlin可以寫成這樣

private fun Bitmap.getRawByteArray() = ByteBuffer.allocate(rowBytes * height).apply {
copyPixelsToBuffer(this)
}.array()

就可以存成檔案。

--

--

JLin
JLin

Written by JLin

台中 / JAVA / Android /Kotlin / Kotlin Native 對於Kotlin衍生的JVM等技術 Compose for web / desktop / Ktor Server,生成式AI (Gemini/OpenAI)各式應用, 都有小興趣

No responses yet