我有以下代碼,它可以正常工作以下載圖像表單url。 我想按下按鈕,將加載到圖像視圖中的圖像保存到SD卡上。 任何人都可以請幫助我如何將下載的圖像保存到SD卡。如何將下載的圖像存儲到android中的sdcard
public class DownloadimageActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void downloadPicture(View view) {
final ProgressDialog dialog = ProgressDialog.show(this, "Snapshot",
"retriving image..");
dialog.show();
new Thread(new Runnable() {
@Override
public void run() {
try {
final Bitmap downloadBitma = downloadBitmap("http://42.60.144.184:8081/snapshot.cgi?&user=admin&pwd=admin&resolution=8");
final ImageView imageView = (ImageView) findViewById(R.id.imageView1);
runOnUiThread(new Runnable() {
@Override
public void run() {
imageView.setImageBitmap(downloadBitma);
}
});
} catch (IOException e) {
e.printStackTrace();
} finally {
dialog.dismiss();
}
}
}).start();
}
private Bitmap downloadBitmap(String url) throws IOException {
HttpUriRequest request = new HttpGet(url.toString());
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
byte[] bytes = EntityUtils.toByteArray(entity);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
bytes.length);
return bitmap;
} else {
throw new IOException("Retrive failed, HTTP response code "
+ statusCode + " - " + statusLine.getReasonPhrase());
}
}
}
我試着用下面的代碼,但它不工作。
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
downloadBitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
//you can create a new file name "test.jpg" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.jpg");
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
你是什麼意思「它不工作」?什麼失敗?它是否會拋出異常?另外,您是否請求了寫入外部存儲的權限? – kabuko
在eclipse中它要求創建一個新變量downloadBitmap – radish
Eclipse是否要求你的代碼在上面的某一行? –