[英]How to convert image into Hex String in android?
我需要將圖像轉換為十六進制字符串以將其發送到 Web 服務器。 我正在使用這種方法將圖像轉換為字節數組
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap receipt = BitmapFactory.decodeFile(photo.toString(),options);
int size = receipt.getRowBytes() * receipt.getHeight();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
receipt.compress(Bitmap.CompressFormat.JPEG, 90, stream);
receiptbyte = stream.toByteArray();
String hexstring = toHex(receiptbyte);
這要轉換為十六進制
public static String toHex(byte[] bytes) {
BigInteger bi = new BigInteger(1, bytes);
return String.format("%0" + (bytes.length << 1) + "X", bi);
}
我想像這樣產生輸出
c11ee236-8f72-4b60-9208-79977d61993f
我不知道該怎么做。 我需要編碼嗎?
您擁有的字符串如c11ee236-8f72-4b60-9208-79977d61993f
不是圖像 - 它看起來更像是存儲在服務器上的圖像的 ID。
如果您想要圖像,您必須將 ID 發送到服務器,服務器將存儲在屬於該 ID 的數據庫中的圖像數據發回。
在 Java 中,您可以簡單地自己生成這樣的隨機 ID:
UUID u = UUID.randomUUID();
System.out.println(u.toString());
輸出例如: 3aa5b32d-c6fb-43c5-80c9-78a1a35aff40
構建您自己的服務器,您可以使用它並將圖像數據和此 ID 保存到數據庫中。
你可以這樣做
//encode image to base64 string
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);
//decode base64 string to image
imageBytes = Base64.decode(imageString, Base64.DEFAULT);
Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
image.setImageBitmap(decodedImage);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.