Unable to save image from Json response using Volley - android

Save Image from ImageView in android Not Working. Image loading By Volley from JSON . I want to save that image in Gallery but on some devices this code not working.
BitmapDrawable draw = (BitmapDrawable) thumbnail.getDrawable();
Bitmap bitmap = draw.getBitmap();
FileOutputStream outStream = null;
File dir = new File(Environment.getExternalStorageDirectory() + "");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
try {
outStream = new FileOutputStream(outFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
try {
outStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(JobsDetail.this, "Download Successfully", Toas.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(dir));
sendBroadcast(intent);

Simply use this to download directly from Image Url
// DownloadImage AsyncTask
private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected Bitmap doInBackground(String... URL) {
String imageURL = URL[0];
Bitmap bitmap = null;
try {
// Download Image from URL
InputStream input = new java.net.URL(imageURL).openStream();
// Decode Bitmap
bitmap = BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
if (result != null) {
progressBar.setVisibility(View.GONE);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
try {
destination.createNewFile();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
result.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(destination);
fos.write(bitmapdata);
fos.flush();
fos.close();
LicenseFrontFile = destination;
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Set the bitmap into ImageView
//image.setImageBitmap(result);
// Close progressdialog
}
To use , call this way
new DownloadImage().execute(image_url);
Add write permissions in manifest also
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And runtime persmissions for Marshmallow or above devices

Create a class SaveImageHelper code is below
public class SaveImageHelper implements Target {
private Context context;
private WeakReference<AlertDialog> mDialog;
private WeakReference<ContentResolver> contentResolverWeakReference;
private String name;
private String desc;
public SaveImageHelper(Context context,AlertDialog alertDialog, ContentResolver contentResolver, String name, String desc) {
this.context = context;
this.mDialog = new WeakReference<AlertDialog>(alertDialog);
this.contentResolverWeakReference = new WeakReference<ContentResolver>(contentResolver);
this.name = name;
this.desc = desc;
}
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
ContentResolver r = contentResolverWeakReference.get();
AlertDialog dialog = mDialog.get();
if(r != null)
MediaStore.Images.Media.insertImage(r,bitmap,name,desc);
dialog.dismiss();
Toast.makeText(context, "Image Download Successfully...", Toast.LENGTH_SHORT).show();
//Open Gallery After Download
//Intent intent = new Intent();
//intent.setType("image/*");
// intent.setAction(Intent.ACTION_GET_CONTENT);
// context.startActivity(Intent.createChooser(intent,"SELECT PICTURE"));
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
and Use it in another class / Activity by button click
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(ActivityCompat.checkSelfPermission(JobsDetail.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(JobsDetail.this, "You Should Grant Permission..", Toast.LENGTH_SHORT).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
}, PERMISSION_REQUEST_CODE);
}
return;
}
else{
AlertDialog dialog = new SpotsDialog(JobsDetail.this);
dialog.show();
dialog.setMessage("Downloading....");
String filename = UUID.randomUUID().toString()+".jpg";
Picasso.with(getBaseContext())
.load(imageUrl)
.into(new SaveImageHelper(getBaseContext(),
dialog, getApplicationContext().getContentResolver(),
filename,"Image Descp"));
}
Also set Permission in oncreate to access files and images in device
if(ActivityCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
}, PERMISSION_REQUEST_CODE);
}

Related

Save Image in External Storage By using Picasso from Url , how to download image and show it in imageview

Please Use This Code for save image in your external Storage by using Url
//Please Put your Image url In $url
Picasso.get().load($url).into(object : Target{
override fun onPrepareLoad(placeHolderDrawable: Drawable?) {
}
override fun onBitmapFailed(e: java.lang.Exception?, errorDrawable: Drawable?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onBitmapLoaded(bitmap: Bitmap?, from: Picasso.LoadedFrom?) {
try {
val root = Environment.getExternalStorageDirectory().toString()
var myDir = File("$root")
if (!myDir.exists()) {
myDir.mkdirs()
}
val name = Date().toString() + ".jpg"
myDir = File(myDir, name)
val out = FileOutputStream(myDir)
bitmap?.compress(Bitmap.CompressFormat.JPEG, 90, out)
out.flush()
out.close()
} catch (e: Exception) {
// some action
}
}
})
and Image will be saved in sdcard.
1- add to AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2- Use this method to download image using Picasso from Url:
private static void SaveImage(final Context context, final String MyUrl){
final ProgressDialog progress = new ProgressDialog(context);
class SaveThisImage extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progress.setTitle("Processing");
progress.setMessage("Please Wait...");
progress.setCancelable(false);
progress.show();
}
#Override
protected Void doInBackground(Void... arg0) {
try{
File sdCard = Environment.getExternalStorageDirectory();
#SuppressLint("DefaultLocale") String fileName = String.format("%d.jpg", System.currentTimeMillis());
File dir = new File(sdCard.getAbsolutePath() + "/savedImageName");
dir.mkdirs();
final File myImageFile = new File(dir, fileName); // Create image file
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myImageFile);
Bitmap bitmap = Picasso.get().load(MyUrl).get();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(myImageFile));
context.sendBroadcast(intent);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}catch (Exception e){
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(progress.isShowing()){
progress.dismiss();
}
Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
}
}
SaveThisImage shareimg = new SaveThisImage();
shareimg.execute();
}
3- how to use, just call:
SaveImage(context, "Image URL");
Use this method to download image in internal memory
// DownloadImage AsyncTask
private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Bitmap doInBackground(String... URL) {
String imageURL = URL[0];
Bitmap bitmap = null;
try {
// Download Image from URL
InputStream input = new java.net.URL(imageURL).openStream();
// Decode Bitmap
bitmap = BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
if (result != null) {
File destination = new File(getActivity().getCacheDir(),
"profile" + ".jpg");
try {
destination.createNewFile();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
result.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(destination);
fos.write(bitmapdata);
fos.flush();
fos.close();
selectedFile = destination;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
And call this method like this
Picasso.get().load(response.body()?.url).into(object : Target{
override fun onPrepareLoad(placeHolderDrawable: Drawable?) {
}
override fun onBitmapFailed(e: java.lang.Exception?, errorDrawable: Drawable?) {
}
override fun onBitmapLoaded(bitmap: Bitmap?, from: Picasso.LoadedFrom?) {
new DownloadImage().execute("url_here);
}
})
Note:- Copy this code and paste it , Kotlin converter will
automatically convert it to Kotlin

How to read an image from internal storage

I have downloaded an image to my app data/data/package memory. it is downloaded, but problem is that i did not got path to display image in imageviewer. but could not. please tell me how to display. Please attention on path. thank you
Here is my download code.
ImageView imageView = (ImageView) findViewById(R.id.iv);
String mUrl = "https://cometonice.com/im.gif";
InputStreamVolleyRequest request = new InputStreamVolleyRequest(Request.Method.GET, mUrl,
new Response.Listener<byte[]>() {
#Override
public void onResponse(byte[] response) {
// TODO handle the response
try {
if (response != null) {
FileOutputStream outputStream;
String name = "im.gif";
outputStream = openFileOutput(name, Context.MODE_PRIVATE);
outputStream.write(response);
outputStream.close();
Toast.makeText(MainActivity.this, "Download complete.", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("KEY_ERROR", "UNABLE TO DOWNLOAD FILE");
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO handle the error
error.printStackTrace();
}
}, null);
RequestQueue mRequestQueue = Volley.newRequestQueue(getApplicationContext(), new HurlStack());
mRequestQueue.add(request);
Well you can use The ImageRequest of volley like this :
ImageRequest request = new ImageRequest(url,
new Response.Listener<Bitmap>() {
#Override
public void onResponse(Bitmap bitmap) {
imageView.setImageBitmap(bitmap);
saveBitmapToFile(bitmap)
}
}, 0, 0, null,
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
}
});
and save it like :
public String saveBitmapToFile(Bitmap bitmap) {
FileOutputStream out = null;
String filename = null;
try {
File f = new File(Environment.getExternalStorageDirectory(), "myapp");
if (!f.exists()) {
f.mkdirs();
}
filename = Environment.getExternalStorageDirectory().getAbsolutePath() + "/myapp/" + UUID.randomUUID().toString() + ".jpg";
out = new FileOutputStream(filename);
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, out);
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return filename;
}

load image from URL and save on memory in android

How to load image from URL and save that on memory of device in android? Dont say me use Picasso or oser laibrary.
I need to:
If device get internet conection I load image to ImageView from url and save it on memory of device, else I need to load one of save image to imageView. Thank`s for helps
P.S. Sorry me, I can make some mistakes in question because I don`t very good know English.
This my class:
public class ImageManager {
String file_path;
Bitmap bitmap = null;
public Bitmap donwoaledImageFromSD() {
File image = new File(Environment.getExternalStorageDirectory().getPath(),file_path);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
return bitmap;
}
private void savebitmap() {
File file = new File("first");
file_path = file.getAbsolutePath();
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90,fileOutputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
public void fetchImage(final String url, final ImageView iView) {
new AsyncTask<String, Void, Bitmap>() {
protected Bitmap doInBackground(String... iUrl) {
try {
InputStream in = new URL(url).openStream();
bitmap = BitmapFactory.decodeStream(in);
savebitmap();
} catch (Exception e) {
donwoaledImageFromSD();
}
return bitmap;
}
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (iView != null) {
iView.setImageBitmap(result);
}
}
}.execute(url);
}
}
Try to use this code:
Method for loading image from imageUrl
public Bitmap getBitmapFromURL(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection)
url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
Bitmap imageBitmap = BitmapFactory.decodeStream(inputStream);
return imageBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
And You should use it in a separate thread, like that:
new Thread(new Runnable() {
#Override
public void run() {
try {
Bitmap bitmap = getBitmapFromURL(<URL of your image>);
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
}
}).start();
But using Picasso - indeed a better way.
Update:
For saving Bitmap to file on external storage (SD card) You can use method like this:
public static void writeBitmapToSD(String aFileName, Bitmap aBitmap) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return;
}
File sdPath = Environment.getExternalStorageDirectory();
File sdFile = new File(sdPath, aFileName);
if (sdFile.exists()) {
sdFile.delete ();
}
try {
FileOutputStream out = new FileOutputStream(sdFile);
aBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
}
}
Remember that You need
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
for it.
And for loading `Bitmap` from file on external storage You can use method like that:
public static Bitmap loadImageFromSD(String aFileName) {
Bitmap result = null;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
try {
FileInputStream fis = new FileInputStream(new File(Environment.getExternalStorageDirectory(), aFileName));
result = BitmapFactory.decodeStream(fis);
fis.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "loadImageFromSD: " + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
You need
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
to do this.
Update 2
Method getBitmapFromURL(), but ImageView should be updated from UI thread, so You should call getBitmapFromURL(), for example, this way:
new Thread(new Runnable() {
#Override
public void run() {
try {
final Bitmap bitmap = getBitmapFromURL("<your_image_URL>");
runOnUiThread(new Runnable() {
#Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
}
}).start();
I had this same issue and I hope this helps. First, To download Image from URL into your app, use the code below:
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
In order for the image to be displayed inside the app, use the method below in your onCreate method:
new DownloadImageTask((ImageView) -your imageview id-)
.execute(-your URL-);
In order for the image to be saved INTERNALLY inside the app/phone, use the code below:
#SuppressLint("WrongThread")
protected void onPostExecute(Bitmap result) {
if (result != null) {
File dir = new File(peekAvailableContext().getFilesDir(), "MyImages");
if(!dir.exists()){
dir.mkdir();
}
File destination = new File(dir, "image.jpg");
try {
destination.createNewFile();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
result.compress(Bitmap.CompressFormat.PNG, 0, bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(destination);
fos.write(bitmapdata);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
bmImage.setImageBitmap(result);
}
}
To load the image from the internal storage, use the code below:
private void loadImageFromStorage(String path)
{
try {
File f=new File(path, "image.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
ImageView img=(ImageView)findViewById(R.id.businessCard_iv);
img.setImageBitmap(b);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
Things to note: 1. path is the a string containing the path of the file. 2. "image.jpg" is the file name so ensure that matches with yours. 3. "MyImages" is a folder in your path which contains the actual saved image.

save multiple images from url into internal storage in android

i am using this method to get images from url and i am downloading more than one image the varable below called "name" is an array of names of the images .i want to be able to store all images whos name is in the array thats why i kept the url like that.it seems to work well but i have having problem selecting only one picture out or them.
this is the code to save images
String fileName="code";
try {
URL url = new URL("http://10.0.2.2/picure/"+name+".jpg");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
Bitmap bm = BitmapFactory.decodeStream(is);
FileOutputStream fos = getActivity().openFileOutput(fileName, Context.MODE_PRIVATE);
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
byte[] byteArray = outstream.toByteArray();
fos.write(byteArray);
fos.close();
Toast.makeText(getActivity()," connected", Toast.LENGTH_LONG).show();
} catch(Exception e) {
}
this is the code to collect images
String path = mContext.getFilesDir().toString();
String fileName = "code";
if (fileName != null && !fileName.equals("")) {
Bitmap bMap = BitmapFactory.decodeFile(path + "/" + fileName);
if (bMap != null) {
category_logo.setImageBitmap(bMap);
}
}
i know the names of the images i saved so how do i select that one specifically
For get all images use a Asynctask, this code can download images in cache directory of the app:
class ImageDownloader extends AsyncTask<String, Void, File> {
String imageurl;
String name;
Context ctx;
public ImageDownloader(Context context, String url, String fileName) {
this.imageurl = url;
this.name = fileName;
this.ctx = context;
}
#Override
protected File doInBackground(String... urls) {
Bitmap mIcon;
File cacheDir = ctx.getCacheDir();
File f = new File(cacheDir, name);
try {
InputStream in = new java.net.URL(imageurl).openStream();
mIcon = BitmapFactory.decodeStream(in);
try {
FileOutputStream out = new FileOutputStream(
f);
mIcon.compress(
Bitmap.CompressFormat.JPEG,
100, out);
out.flush();
out.close();
return f;
} catch (FileNotFoundException e) {
return null;
} catch (IOException e) {
return null;
}
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(File result) {
super.onPostExecute(result);
Toast.makeText(ctx," connected " + name, Toast.LENGTH_LONG).show();
}
}
}
For call the asynctask, you need use a FOR for get all names and url of the image:
new ImageDownloader(getBaseContext(),url[i],name[i]).execute();
You can edit the doInBackground with your code, but the HTTPConnection that you use is deprecated in API 22, please use the example above, you can change the directory.
And sorry for the code, you can reformat later.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CODE_MULTIPLE_IMG_GALLERY && resultCode==RESULT_OK){
ClipData clipData = data.getClipData();
if (clipData!=null){
File folderPath = new File(getIntent().getStringExtra("folderpath"));
for (int i = 0;i< clipData.getItemCount();i++){
ClipData.Item item = clipData.getItemAt(i);
Uri uri = item.getUri();
Bitmap selectedImage = loadFromUri(uri);
File imagePath = new File(folderPath,System.currentTimeMillis()+".jpg");
try {
outputStream = new FileOutputStream(imagePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
selectedImage.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
Log.d("uri",uri.toString());
imageModelList.add(new ImageModel(uri.toString()));
}
imagesAdapter.notifyDataSetChanged();
Toast.makeText(ImageDetailActivity.this, "Added Successfully!", Toast.LENGTH_SHORT).show();
}
}
}
public Bitmap loadFromUri(Uri photoUri) {
Bitmap image = null;
try {
// check version of Android on device
if(Build.VERSION.SDK_INT > 27){
// on newer versions of Android, use the new decodeBitmap method
ImageDecoder.Source source = ImageDecoder.createSource(this.getContentResolver(), photoUri);
image = ImageDecoder.decodeBitmap(source);
} else {
// support older versions of Android by using getBitmap
image = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoUri);
}
} catch (IOException e) {
e.printStackTrace();
}
return image;
}

Best method to download image from url in Android

I'm using below method to download single image from url
public static Bitmap getBitmap(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Bitmap d = BitmapFactory.decodeStream(is);
is.close();
return d;
} catch (Exception e) {
return null;
}
}
Sometimes I get an outofmemory exception.
I am unable to catch outofmemory exception. The app will close. How to prevent this?
Is there a better method for downloading images that is also faster?
public void DownloadImageFromPath(String path){
InputStream in =null;
Bitmap bmp=null;
ImageView iv = (ImageView)findViewById(R.id.img1);
int responseCode = -1;
try{
URL url = new URL(path);//"http://192.xx.xx.xx/mypath/img1.jpg
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setDoInput(true);
con.connect();
responseCode = con.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK)
{
//download
in = con.getInputStream();
bmp = BitmapFactory.decodeStream(in);
in.close();
iv.setImageBitmap(bmp);
}
}
catch(Exception ex){
Log.e("Exception",ex.toString());
}
}
Step 1: Declaring Permission in Android Manifest
First thing to do in your first Android Project is you declare required permissions in your ‘AndroidManifest.xml’ file.
For Android Download Image from URL, we need permission to access the internet to download file and read and write internal storage to save image to internal storage.
Add following lines of code at the top of tag of AndroidManifest.xml file:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Step 2: Request required permission from user
Android allows every app to run in a sandbox. If an app needs to access certain resources or information outside that sandbox, it needs to request permission from user.
From Android 6.0 onward, Google wants developers to request permission from user from within the app, for more details on permissions read this.
Therefore for Android Download Image from URL, you’ll need to request Read Storage and Write
For this, we will use the following lines of code to first check if the required permission is already granted by the user, if not then we will request permission for storage read and write permission.
We’re creating a method ‘Downlaod Image’, you can simple call this wherever you need to download the image.
void DownloadImage(String ImageUrl) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 123);
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 123);
showToast("Need Permission to access storage for Downloading Image");
} else {
showToast("Downloading Image...");
//Asynctask to create a thread to downlaod image in the background
new DownloadsImage().execute(ImageUrl);
}
}
Now that we have requested and been granted the user permission, to start with android download image from url, we will create an AsyncTask, as you are not allowed to run a background process in the main thread.
class DownloadsImage extends AsyncTask<String, Void,Void>{
#Override
protected Void doInBackground(String... strings) {
URL url = null;
try {
url = new URL(strings[0]);
} catch (MalformedURLException e) {
e.printStackTrace();
}
Bitmap bm = null;
try {
bm = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
//Create Path to save Image
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES+ "/AndroidDvlpr"); //Creates app specific folder
if(!path.exists()) {
path.mkdirs();
}
File imageFile = new File(path, String.valueOf(System.currentTimeMillis())+".png"); // Imagename.png
FileOutputStream out = null;
try {
out = new FileOutputStream(imageFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try{
bm.compress(Bitmap.CompressFormat.PNG, 100, out); // Compress Image
out.flush();
out.close();
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(MainActivity.this,new String[] { imageFile.getAbsolutePath() }, null,new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
// Log.i("ExternalStorage", "Scanned " + path + ":");
// Log.i("ExternalStorage", "-> uri=" + uri);
}
});
} catch(Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
showToast("Image Saved!");
}
}
In the above give lines of code, a URL and Bitmap is created, using BitmapFactory.decodeStream, file is downloaded.
The File path is created to save the image (We have created a folder named ‘AndroidDvlpr’ in DIRECTORY_PICTURES) and download is initialized.
After downloading the file MediaScannerConnection, is called to read metadata from the file and add the file to the media content provider so the image is available for the user.
In the above lines of code, we have also created a method, showToast() to show Toast. complete code here:
void showToast(String msg){
Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show();
}
Read more here
Add This Dependency For Android Networking Into Your Project
compile 'com.amitshekhar.android:android-networking:1.0.0'
String url = "http://ichef.bbci.co.uk/onesport/cps/480/cpsprodpb/11136/production/_95324996_defoe_rex.jpg";
File file;
String dirPath, fileName;
Button downldImg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialization Of DownLoad Button
downldImg = (Button) findViewById(R.id.DownloadButton);
// Initialization Of DownLoad Button
AndroidNetworking.initialize(getApplicationContext());
//Folder Creating Into Phone Storage
dirPath = Environment.getExternalStorageDirectory() + "/Image";
fileName = "image.jpeg";
//file Creating With Folder & Fle Name
file = new File(dirPath, fileName);
//Click Listener For DownLoad Button
downldImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AndroidNetworking.download(url, dirPath, fileName)
.build()
.startDownload(new DownloadListener() {
#Override
public void onDownloadComplete() {
Toast.makeText(MainActivity.this, "DownLoad Complete", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(ANError anError) {
}
});
}
});
}
}
After Run This Code
Check Your Phone Memory
You Can See There A Folder - Image
Check Inside This Folder , You see There a Image File with name of "image.jpeg"
Thank You !!!
You can download image by Asyn task
use this class:
public class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private final MemoryCache memoryCache;
private final BrandItem brandCatogiriesItem;
private Context context;
private String url;
public ImageDownloaderTask(ImageView imageView, String url, Context context) {
imageViewReference = new WeakReference<ImageView>(imageView);
memoryCache = new MemoryCache();
brandCatogiriesItem = new BrandItem();
this.url = url;
this.context = context;
}
#Override
protected Bitmap doInBackground(String... params) {
return downloadBitmap(params[0]);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
memoryCache.put("1", bitmap);
brandCatogiriesItem.setUrl(url);
brandCatogiriesItem.setThumb(bitmap);
// BrandCatogiriesItem.saveLocalBrandOrCatogiries(context, brandCatogiriesItem);
imageView.setImageBitmap(bitmap);
} else {
Drawable placeholder = imageView.getContext().getResources().getDrawable(R.drawable.placeholder);
imageView.setImageDrawable(placeholder);
}
}
}
}
private Bitmap downloadBitmap(String url) {
HttpURLConnection urlConnection = null;
try {
URL uri = new URL(url);
urlConnection = (HttpURLConnection) uri.openConnection();
int statusCode = urlConnection.getResponseCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
Log.d("URLCONNECTIONERROR", e.toString());
if (urlConnection != null) {
urlConnection.disconnect();
}
Log.w("ImageDownloader", "Error downloading image from " + url);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
}
And call this like:
new ImageDownloaderTask(thumbImage, item.thumbnail, context).execute(item.thumbnail);
I recommend using the altex-image-downloader library, which makes it easy to download images:
AltexImageDownloader.writeToDisk(context, Imageurl, "IMAGES");
Add dependency in app build gradle:
implementation 'com.artjimlop:altex-image-downloader:0.0.4'
The OOM exception could be avoided by following the official guide to load large bitmap.
Don't run your code on the UI Thread. Use AsyncTask instead and you should be fine.
you can use below function to download image from url.
private Bitmap getImage(String imageUrl, int desiredWidth, int desiredHeight)
{
private Bitmap image = null;
int inSampleSize = 0;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inSampleSize = inSampleSize;
try
{
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
InputStream stream = connection.getInputStream();
image = BitmapFactory.decodeStream(stream, null, options);
int imageWidth = options.outWidth;
int imageHeight = options.outHeight;
if(imageWidth > desiredWidth || imageHeight > desiredHeight)
{
System.out.println("imageWidth:"+imageWidth+", imageHeight:"+imageHeight);
inSampleSize = inSampleSize + 2;
getImage(imageUrl);
}
else
{
options.inJustDecodeBounds = false;
connection = (HttpURLConnection)url.openConnection();
stream = connection.getInputStream();
image = BitmapFactory.decodeStream(stream, null, options);
return image;
}
}
catch(Exception e)
{
Log.e("getImage", e.toString());
}
return image;
}
See complete explanation here
public class testCrop extends AppCompatActivity {
ImageView iv;
String imagePath = "https://style.pk/wp-content/uploads/2015/07/omer-Shahzad-performed-umrah-600x548.jpg";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testcrpop);
iv = (ImageView) findViewById(R.id.testCrop);
imageDownload image = new imageDownload(testCrop.this, iv);
image.execute(imagePath);
}
class imageDownload extends AsyncTask<String, Integer, Bitmap> {
Context context;
ImageView imageView;
Bitmap bitmap;
InputStream in = null;
int responseCode = -1;
//constructor.
public imageDownload(Context context, ImageView imageView) {
this.context = context;
this.imageView = imageView;
}
#Override
protected void onPreExecute() {
}
#Override
protected Bitmap doInBackground(String... params) {
URL url = null;
try {
url = new URL(params[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
responseCode = httpURLConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
in = httpURLConnection.getInputStream();
bitmap = BitmapFactory.decodeStream(in);
in.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap data) {
imageView.setImageBitmap(data);
}
}
}
OUTPUT
I'm still learning Android, so I cannot provide a rich context or reason for my suggestion, but this is what I am using to retrive files from both https and local urls. I am using this in my onActivity result (for both taking pictures and selecting from gallery), as well in an AsyncTask to retrieve the https urls.
InputStream input = new URL("your_url_string").openStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
First Declare Permission in Android Manifest:-
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
MainActivityForDownloadImages.java
public class MainActivityForDownloadImages extends AppCompatActivity {
// String urls = "https://stimg.cardekho.com/images/carexteriorimages/930x620/Kia/Kia-Seltos/6232/1562746799300/front-left-side-47.jpg";
String urls = "https://images5.alphacoders.com/609/609173.jpg";
Button button;
public final Context context = this;
ProgressDialog progressDialog ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_for_download_images);
if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
progressDialog = new ProgressDialog(context);
button = findViewById(R.id.downloadImagebtn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// initialize the progress dialog like in the first example
// this is how you fire the downloader
Intent intent = new Intent(context, DownloadService.class);
intent.putExtra("url", urls);
intent.putExtra("receiver", new DownloadReceiver(new Handler()));
startService(intent);
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 0) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
}
}
}
private class DownloadReceiver extends ResultReceiver {
public DownloadReceiver(Handler handler) {
super(handler);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
if (resultCode == DownloadService.UPDATE_PROGRESS) {
int progress = resultData.getInt("progress"); //get the progress
progressDialog.setProgress(progress);
progressDialog.setMessage("Images Is Downloading");
progressDialog.show();
if (progress == 100) {
progressDialog.dismiss();
}
}
}
}
}
DownloadService.java
public class DownloadService extends IntentService {
public static final int UPDATE_PROGRESS = 8344;
String folder_main = "ImagesFolder";
public DownloadService() {
super("DownloadService");
}
#Override
protected void onHandleIntent(Intent intent) {
String urlToDownload = intent.getStringExtra("url");
ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
try {
//create url and connect
URL url = new URL(urlToDownload);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(connection.getInputStream());
File outerFolder = new File(Environment.getExternalStorageDirectory(), folder_main);
File inerDire = new File(outerFolder.getAbsoluteFile(), System.currentTimeMillis() + ".jpg");
if (!outerFolder.exists()) {
outerFolder.mkdirs();
}
inerDire.createNewFile();
FileOutputStream output = new FileOutputStream(inerDire);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
Bundle resultData = new Bundle();
resultData.putInt("progress", (int) (total * 100 / fileLength));
receiver.send(UPDATE_PROGRESS, resultData);
output.write(data, 0, count);
}
// close streams
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
Bundle resultData = new Bundle();
resultData.putInt("progress", 100);
receiver.send(UPDATE_PROGRESS, resultData);
}
}
Try this code to download an image from a URL on Android:
DownloadManager downloadManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(imageName);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Long reference = downloadManager.enqueue(request);
You can use this function to save your bitmap/image in gallery for all android version including Android 11
private fun addImageToGallery(fileName: String, bitmap: Bitmap, ctx: Context) {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val fos: OutputStream
val resolver = contentResolver
val values = ContentValues()
values.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
values.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
values.put(
MediaStore.MediaColumns.RELATIVE_PATH,
Environment.DIRECTORY_PICTURES + File.separator + "EduImages"
)
val imageUri = resolver.insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values
)
fos = resolver.openOutputStream(imageUri!!) as OutputStream
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
fos.close()
Toast.makeText(
ctx, "Saved in gallery",
Toast.LENGTH_SHORT
).show()
} else {
val values = ContentValues()
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
values.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, fileName)
values.put(MediaStore.Images.ImageColumns.TITLE, fileName)
val uri: Uri? = ctx.contentResolver.insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values
)
uri?.let {
ctx.contentResolver.openOutputStream(uri)?.let { stream ->
val oStream =
BufferedOutputStream(stream)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, oStream)
oStream.close()
Toast.makeText(ctx, "Saved in gallery", Toast.LENGTH_SHORT)
.show()
}
}
}
} catch (e: Exception) {
Toast.makeText(ctx, e.localizedMessage, Toast.LENGTH_SHORT).show()
}
}

Categories

Resources