在这里,我尝试从服务器下载图像。但它总是抛出异常。任何人都可以告诉我为什么会发生这种情况以及正确的方法是什么?
public static String getBitmap(String url) throws IOException {
InputStream is = (InputStream) new URL(url).getContent();
Bitmap bmp= BitmapFactory.decodeStream(is);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] b=stream.toByteArray();
String encoded = Base64.encodeToString(b, Base64.DEFAULT);
is.close();
return encoded;
}
请尝试此功能获取位图并下载位图
Bitmap bitmap = getBitmapfromUrl(imageurl);
imageview.setImageBitmap(bitmap);
SaveImage(bitmap);
public Bitmap getBitmapfromUrl(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
return bitmap;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
private void SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n;
File file = new File(myDir, fname);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
并在您的清单文件中添加此权限
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)