Android - 在外部存储器上使用其URL保存图片
问题描述:
我已经搜索并尝试了一切,我在Google和*上发现了关于此主题的所有内容,但是我没有找到使其工作。 我有这个代码,但它引发了我一个致命的例外。 我认为,因为我是Android新手,所以我做错了一些事情。请帮助我^^Android - 在外部存储器上使用其URL保存图片
public void svgPhoto() throws IOException {
String dir = Environment.getExternalStorageDirectory().toString();
OutputStream fos = null;
File file = new File(dir,"downloadImage.JPEG");
Bitmap bm =BitmapFactory.decodeFile("http://perlbal.hi-pi.com/blog-images/3278/gd/1242316719/Chat-chat.jpg");
fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bm.compress(Bitmap.CompressFormat.JPEG, 50, bos);
bos.flush();
bos.close();
答
公共类下载扩展的AsyncTask {
@Override
protected Void doInBackground(Void... params)
{
try {
URL url = new URL(imageURL);
file2 = new File(fileName);
long startTime = System.currentTimeMillis();
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file2);
fos.write(baf.toByteArray());
fos.close();
Log.d("ImageManager",
"download ready in"
+ ((System.currentTimeMillis() - startTime)/1000)
+ " sec");
} catch (IOException e) {
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
try {
try {
File fileWithinMyDir = getApplicationContext().getFilesDir();
String PATH = fileWithinMyDir.getAbsolutePath();
Drawable d = Drawable.createFromPath(PATH.toString());
Bitmap bmp = ((BitmapDrawable) d).getBitmap();
} catch (Exception e) {
e.printStackTrace();
}
if (dialog != null) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
答
尝试下一编码:
String dir = Environment.getExternalStorageDirectory().toString();
File outputfile = new File(dir+"/downloadImage.JPEG");
OutputStream fOut = null;
try {
fOut = new FileOutputStream(outputfile);
Bitmap bm =BitmapFactory.decodeFile("http://perlbal.hi-pi.com/blog-images/3278/gd/1242316719/Chat-chat.jpg");
bm.compress(CompressFormat.JPEG, 50, fOut);
} catch (IOException e) {
Logger.error(e.getMessage(), e);
}finally{
try {
if(fOut != null){
fOut.flush();
fOut.close();
}
} catch (IOException e) {
Logger.error(e.getMessage(), e);
}
}
确保您有'WRITE_EXTERNAL_STORAGE'许可,您的AndroidManifest.xml – 2013-02-28 14:26:00