一、Bitmap是什麼
Bitmap是Android操作系統中用於表示圖像的類,可以表示壓縮或非壓縮的圖像。
在Android中,像素值是以ARGB的形式存儲的,也就是說一個像素點需要佔4個字節的空間。
二、為什麼要將Bitmap轉為Byte
在Android開發過程中,經常需要將位圖(Bitmap)轉換為字節數組(Byte)以便於網絡傳輸或保存到本地。另一方面,在Python中操作字節數組更加容易。
三、如何實現Bitmap轉Byte
在Android中,我們可以通過將Bitmap的像素點轉換為字節數組的方式實現。而在Python中,可以使用Pillow庫來操作圖像並轉換為字節數組。
#Android Java實現 //Bitmap轉Byte public static byte[] bitmap2Bytes(Bitmap bitmap) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); return baos.toByteArray(); } //Byte轉Bitmap public static Bitmap byte2Bitmap(byte[] bytes) { return BitmapFactory.decodeByteArray(bytes, 0, bytes.length); }
#Python實現 from PIL import Image #Bitmap轉Byte def bitmap2bytes(bitmap): img = Image.fromarray(bitmap) img.save("temp.png", format="png") with open("temp.png", "rb") as f: return f.read() #Byte轉Bitmap def bytes2bitmap(bytes): img = Image.open(io.BytesIO(bytes)) return np.array(img)
上述代碼使用了Pillow庫的Image類將Bitmap轉為臨時的PNG圖片,然後將PNG圖片轉換為字節數組,實現了Bitmap到Byte的轉換。
四、使用示例
下面是Android Java和Python的示例代碼:
//Android Java Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.test); byte[] bytes = Utils.bitmap2Bytes(bitmap); //Python from urllib.request import urlopen import numpy as np response = urlopen('https://www.example.com/test.png') image_data = response.read() bitmap = np.asarray(bytearray(image_data), dtype="uint8") bytes = bitmap2bytes(bitmap)
上述示例代碼展示了在Android和Python中如何將位圖(Bitmap)轉換成字節數組(Byte)。
五、總結
Bitmap和Byte在Android開發過程中經常需要相互轉換,本文介紹了Java和Python兩種語言實現的方式,並提供了相關代碼示例。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/195859.html