Image Download
//oncreate
new LoadImageTask(this).execute(url);
//implements
LoadImageTask.Listener
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
/* String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/Qrcode_Fast";
File dir = new File(file_path);
if(!dir.exists())
dir.mkdirs();
try {
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
String mImageName = "MI_" + timeStamp + ".jpg";
File tempFile = new File(getFilesDir(), mImageName);
OutputStream outputStream = null;
outputStream = new FileOutputStream(tempFile);
image.compress(Bitmap.CompressFormat.JPEG, 70, outputStream);
outputStream.flush();
outputStream.close();
}catch (Exception e)
{
e.printStackTrace();
}*/
if (pictureFile == null) {
Log.d("error",
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d("error", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("error", "Error accessing file: " + e.getMessage());
}
}
private File getOutputMediaFile(){
/* File tempFile = new File(getFilesDir(), imageFileName);
OutputStream outputStream = null;
outputStream = new FileOutputStream(tempFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, outputStream);
outputStream.flush();
outputStream.close();*/
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/Qrcode_Save_Jins";
File dir = new File(file_path);
if(!dir.exists())
dir.mkdirs();
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! dir.exists()){
if (! dir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(dir.getPath() + File.separator + mImageName);
return mediaFile;
}
public class LoadImageTask extends AsyncTask<String, Void, Bitmap> {
public LoadImageTask(Listener listener) {
mListener = listener;
}
public interface Listener{
void onImageLoaded(Bitmap bitmap);
void onError();
}
private LoadImageTask.Listener mListener;
@Override
protected Bitmap doInBackground(String... args) {
try {
return BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
mListener.onImageLoaded(bitmap);
} else {
mListener.onError();
}
}
}