i have the following code which works fine to download image form url .
i want to save the image loaded in the imageview to sdcard on a button click.
can anyone please help me how can i save the downloaded image to 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());
}
}
}
i tried with the following code but it doesnt work.
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());
Your Bitmap name is missing the ‘p’ at the end so this won’t work…
Oh, and don’t give a variable the same name as a method – I don’t even know if that is legal in Java.