如何从URL下载gif图像并保存到Android中的存储

时间:2018-12-28 09:50:59

标签: java android image gif android-glide

我想在我的应用程序中添加功能,以将GIF图片从url下载到手机存储中。 如何在我的应用程序中做到这一点

public class Download {

    Context context;
    String url;
    ProgressDialog progressDailog;

    public void saveImage(Context context, String url) {

        this.context = context;
        this.url = url;

        progressDailog = new ProgressDialog(context);
        progressDailog.setMax(100);
        progressDailog.setMessage("Please wait...");
        progressDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDailog.setCanceledOnTouchOutside(false);
        progressDailog.show();


        Glide.with(context).asBitmap()
                .load(url)
                .apply(new RequestOptions()
                        .diskCacheStrategyOf(DiskCacheStrategy.ALL)
                        .format(DecodeFormat.PREFER_ARGB_8888)
                        .override(Target.SIZE_ORIGINAL))
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        progressDailog.dismiss();
                        storeImage(resource);
                        //Log.d(TAG, "Image : " + resource);
                    }
                });
    }

    private void storeImage(Bitmap image) {
        File pictureFile = getOutputMediaFile();
        if (pictureFile == null) {
            return;
        }
        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            image.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.close();
            Toast.makeText(context, "Image Downloaded", Toast.LENGTH_SHORT).show();
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
        }
    }

    private File getOutputMediaFile() {
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/Christmas"); /*getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/Christmas/c");*/
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs())
                return null;
        }

        File mediaFile;
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_MERRY_CHRISTMAS.jpg");
        return mediaFile;
    }

}

从此代码中,我可以下载常规图像,但不适用于GIF。 GIF图片已下载,并且保持不变

3 个答案:

答案 0 :(得分:0)

Glide可以获取File,与我一起工作: Glide.with(context).asFile() .load(url) .apply(new RequestOptions() .diskCacheStrategyOf(DiskCacheStrategy.ALL) .format(DecodeFormat.PREFER_ARGB_8888) .override(Target.SIZE_ORIGINAL)) .into(new SimpleTarget<File>() { @Override public void onResourceReady(@NonNull File resource, @Nullable Transition<? super File> transition) { progressDailog.dismiss(); storeImage(resource); //Log.d(TAG, "Image : " + resource); } });

答案 1 :(得分:0)

要使用Glide获取GIF:

 Glide.with(MainActivity.this).asFile()
            .load(url)
            .apply(new RequestOptions()
                    .format(DecodeFormat.PREFER_ARGB_8888)
                    .override(Target.SIZE_ORIGINAL))
            .into(new Target<File>() {
                @Override
                public void onStart() {

                }

                @Override
                public void onStop() {

                }

                @Override
                public void onDestroy() {

                }

                @Override
                public void onLoadStarted(@Nullable Drawable placeholder) {

                }

                @Override
                public void onLoadFailed(@Nullable Drawable errorDrawable) {

                }

                @Override
                public void onResourceReady(@NonNull File resource, @Nullable Transition<? super File> transition) {
                    storeImage(resource);
                }

                @Override
                public void onLoadCleared(@Nullable Drawable placeholder) {

                }

                @Override
                public void getSize(@NonNull SizeReadyCallback cb) {

                }

                @Override
                public void removeCallback(@NonNull SizeReadyCallback cb) {

                }

                @Override
                public void setRequest(@Nullable Request request) {

                }

                @Nullable
                @Override
                public Request getRequest() {
                    return null;
                }
            });

用于保存图像:

 private void storeImage(File image) {
    File pictureFile = getOutputMediaFile();
    if (pictureFile == null) {
        return;
    }
    try {
        FileOutputStream output = new FileOutputStream(pictureFile);
        FileInputStream input = new FileInputStream(image);

        FileChannel inputChannel = input.getChannel();
        FileChannel outputChannel = output.getChannel();

        inputChannel.transferTo(0, inputChannel.size(), outputChannel);
        output.close();
        input.close();
        Toast.makeText(MainActivity.this, "Image Downloaded", Toast.LENGTH_SHORT).show();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private File getOutputMediaFile() {
    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/Christmas"); /*getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/Christmas/c");*/
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs())
            return null;
    }

    File mediaFile;
    mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_MERRY_CHRISTMAS_"+Calendar.getInstance().getTimeInMillis() +".gif");
    return mediaFile;
}

答案 2 :(得分:0)

  

此代码段将帮助您使用GLIDE下载gif

def f = new File('C:\\GroovyTEst.txt') 
def records = f.readLines()
testRunner.testCase.testSuite.project.setPropertyValue("VendorRideid",records[0]) // here the value should be dynamic so that i can read one by one values from the text file 

def tCase = testRunner.testCase.testSuite.testCases["ChangeRidestatus-accepted"]
def tStep = tCase.testSteps["Pending"]
    tStep.run(testRunner, context)
def tStep1 = tCase.testSteps["Change RideStatus - Accepted"]
    tStep1.run(testRunner, context)
  

createName函数

Glide.with(context)
                    .download(url)
                    .listener(new RequestListener<File>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<File> target, boolean isFirstResource) {
                            progressDailog.dismiss();
                            Toast.makeText(context, "Error saving", Toast.LENGTH_SHORT).show();
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(File resource, Object model, Target<File> target, DataSource dataSource, boolean isFirstResource) {
                            progressDailog.dismiss();
                            try {
                                saveGifImage(context, getBytesFromFile(resource), createName(url));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            return true;
                        }
                    }).submit();
  

getBytesFromFile函数

public String createName(String url) {

        String name = url.substring( url.lastIndexOf('/')+1, url.length());
        String NoExt = name.substring(0, name.lastIndexOf('.'));

        if(!ext.equals(".gif")){
            name = NoExt + ".jpg";
        }
        return name;
    }
  

saveGifImage函数

public byte[] getBytesFromFile(File file) throws IOException {
        long length = file.length();
        if (length > Integer.MAX_VALUE) {
            throw new IOException("File is too large!");
        }
        byte[] bytes = new byte[(int) length];
        int offset = 0;
        int numRead = 0;
        InputStream is = new FileInputStream(file);
        try {
            while (offset < bytes.length
                    && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
                offset += numRead;
            }
        } finally {
            is.close();
        }
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file " + file.getName());
        }
        return bytes;
    }