我是android的新手。图片以 Base64 格式存储在服务器中。那么如何才能从服务器到我的项目,并使用Json Object设置为我的ImageView。 请帮帮我
任何帮助都将获得Appappreciated
答案 0 :(得分:2)
试试这个:
首先将Url转换为byte []:
byte[] bitmapdata = getByteArrayImage(url);
方法:
private byte[] getByteArrayImage(String url){
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(500);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
return baf.toByteArray();
} catch (Exception e) {
Log.d("ImageManager", "Error: " + e.toString());
}
return null;
}
现在将byte []转换为位图
Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata , 0, bitmapdata .length);
并将您的位图设置为ImageView:
img= (ImageView) findViewById(R.id.imgView);
img.setImageBitmap(bitmap );
答案 1 :(得分:0)
试试这个:
URL u = new URL(content);
openStream = u.openStream();
int contentLength = openStream.available();
byte[] binaryData = new byte[contentLength];
openStream.read(binaryData);
openStream.close();
答案 2 :(得分:0)
我找到了简单的解决方案:
byte[] img = Base64.decode(userHeader.GetImage(), Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(img, 0, img.length);
imageww.setImageBitmap(getCircleBitmap(bitmap));
答案 3 :(得分:0)
使用Apache的commons-io-2.5 lib我们可以使用这个函数IOUtils.toByteArray(是)
public static String getByteArrayFromURL(final String url) {
String base64Image = "";
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> result = executor.submit(new Callable<String>() {
public String call() throws Exception {
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
InputStream is = ucon.getInputStream();
return Base64.encodeToString(IOUtils.toByteArray(is), Base64.NO_WRAP);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
});
try {
base64Image = result.get();
} catch (Exception exception) {
exception.printStackTrace();
}
return base64Image;
}