我通过图像url表单适配器,并希望从url下载图像,
imageView = (ImageView) findViewById(R.id.image_view);
buttonDownload = (Button)findViewById(R.id.buttonDownload);
String strImage= String.valueOf(getIntent().getStringExtra("URL"));
Glide.with(this)
.load(strImage)
.into(imageView);
buttonDownload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//what to do
}
});
尝试以下方式
通过URL为AsyncTask
图像写入downloading
private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
private String TAG = "DownloadImage";
@Override
protected Bitmap doInBackground(String... params) {
return downloadImageBitmap(params[0]);
}
private Bitmap downloadImageBitmap(String sUrl) {
Bitmap bitmap = null;
try {
InputStream inputStream = new URL(sUrl).openStream(); // Download Image from URL
bitmap = BitmapFactory.decodeStream(inputStream); // Decode Bitmap
inputStream.close();
} catch (Exception e) {
Log.d(TAG, "Exception "+e.toString());
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap result) {
saveImage(context, result, "my_image.jpeg");
}
}
保存图像
public void saveImage(Context context, Bitmap b, String imageName) {
FileOutputStream foStream;
try {
foStream = context.openFileOutput(imageName, Context.MODE_PRIVATE);
b.compress(Bitmap.CompressFormat.PNG, 100, foStream);
foStream.close();
} catch (Exception e) {
Log.d("saveImage", "Exception "+e.toString());
e.printStackTrace();
}
}
现在处于download button click
通话DownloadImage
buttonDownload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new DownloadImage().execute(strImage);
}
});
要加载下载的图像,请调用以下方法。
public Bitmap loadImageBitmap(Context context, String imageName) {
Bitmap bitmap = null;
FileInputStream fiStream;
try {
fiStream = context.openFileInput(imageName);
bitmap = BitmapFactory.decodeStream(fiStream);
fiStream.close();
} catch (Exception e) {
Log.d("saveImage", "Exception 3, Something went wrong!");
e.printStackTrace();
}
return bitmap;
}
// example of show downloaded image
yourImageView.setImageBitmap(loadImageBitmap(context, "my_image.jpeg"));