arinze
arinze

Reputation: 449

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

Upvotes: 1

Views: 2682

Answers (2)

Meet
Meet

Reputation: 915

@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;
}

Upvotes: 1

Santiago
Santiago

Reputation: 1745

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.

Upvotes: 1

Related Questions