【发布时间】:2011-07-27 14:49:33
【问题描述】:
我需要将图片转换为base64格式,然后上传到服务器,然后从服务器检索base64字符串并将其转换回图片...怎么做?
【问题讨论】:
-
上传时必须expand an image by 33%有什么特别的原因吗?对我来说似乎违反直觉。
标签: android file-upload base64
我需要将图片转换为base64格式,然后上传到服务器,然后从服务器检索base64字符串并将其转换回图片...怎么做?
【问题讨论】:
标签: android file-upload base64
首先将位图转换为 Base 64
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bitmap = Bitmap.createScaledBitmap("Your Bitmap Object Here", 100, 100, false);
bitmap = Bitmap.createScaledBitmap(bitmap, 100, 100, false);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encoded = Base64.encodeToString(imageBytes, Base64.NO_WRAP);
然后使用 Json 对象上传如下:
JSONObject jsonObject = new JSONObject();
String withBase = "data:image/jpeg;base64," + encoded;
jsonObject.put("b64", "" + withBase);
System.out.println("base 64 == " + jsonObject.toString());
return jsonObject.toString();
然后您可以在您的响应中检索这些 Base 64 字符串。
然后通过下面将这些Base64转换为位图:
byte[] decodeString = Base64.decode(encodedImage, Base64.DEFAULT); 位图decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
然后在您的图像视图中使用这些位图。
【讨论】:
这篇文章是由想要与你相反的方向发展的人发布的,但答案仍然相关:
converting base64 String to image in android
注意内存不足问题:
OutOfMemoryError: bitmap size exceeds VM budget :- Android
以下是从 Android 应用向服务器发布文件的示例:
http://groups.google.com/group/android-developers/browse_thread/thread/e51d4f74452a1143?tvc=2&pli=1
【讨论】:
使用这个link 并获取 Base64Coder 类。这将帮助您将图像编码为 Base64 字符串并将字符串解码为字节数组。您可以使用该字节制作图像文件。
byte[] stringBytes = your_Base64_String.getBytes();
byte[] img = null;
try {
img = Base64Coder.decode(stringBytes );
} catch (IOException e) {
e.printStackTrace();
}
【讨论】:
public String ConvertBitmapToBase64Format(Bitmap bitmap)
{
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, stream);
byte[] byteFormat = stream.toByteArray();
// get the base 64 string
String imageString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);
return imageString;
}
// then this imageString pass to json object
String encodedImage=ConvertBitmapToBase64Format(bitmap); // pass your image bitmap
JsonObject.put("Key",
encodedImage);
pass this jsonObject to your webservice
【讨论】: