将多个图像从url保存到android中的内部存储中

时间:2015-04-07 20:25:54

标签: android image internal-storage

我正在使用此方法从url获取图像,我正在下载多个图像,下面称为“name”的varable是图像名称的数组。我希望能够存储名称所在的所有图像数组这就是为什么我保持这样的网址。它似乎运作良好,但我有问题只选择一张图片或他们。

这是保存图片的代码

 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) {



            }

这是收集图像的代码

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

我知道我保存的图像的名称,所以我如何选择那个

2 个答案:

答案 0 :(得分:1)

为了让所有图像都使用Asynctask,此代码可以下载应用程序缓存目录中的图像:

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();

            }


        }
    }

要调用asynctask,您需要使用FOR来获取图像的所有名称和URL:

new ImageDownloader(getBaseContext(),url[i],name[i]).execute();

您可以使用您的代码编辑doInBackground,但在API 22中不推荐您使用的HTTPConnection,请使用上面的示例,您可以更改目录。

对于代码感到抱歉,您可以稍后重新格式化。

答案 1 :(得分:1)

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