简体   繁体   English

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

[英]How to download gif images from url and save to storage in android

I want to add feature in my app to download a GIF Image from url to my phones storage. 我想在我的应用程序中添加功能,以将GIF图片从url下载到手机存储中。 How can I do this into my application 我该如何在我的应用程序中做到这一点

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

}

From this code I can download the normal Image but it did not works on GIF. 从此代码中,我可以下载普通图像,但不适用于GIF。 The GIF image downloaded and it remains static GIF图片已下载,并且保持静态

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

For getting GIF using Glide: 使用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;
                }
            });

For Saving Image: 保存图像:

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

This snippet will help you to download gif using GLIDE 此代码段将帮助您使用GLIDE下载gif

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

createName function createName函数

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

getBytesFromFile function getBytesFromFile函数

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

saveGifImage function saveGifImage函数

public void saveGifImage(Context context, byte[] bytes, String imgName ) {
        FileOutputStream fos = null;
        try {

            File externalStoragePublicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            File customDownloadDirectory = new File(externalStoragePublicDirectory, "Merry_Christmas");
            if (!customDownloadDirectory.exists()) {
                boolean isFileMade = customDownloadDirectory.mkdirs();
            }
            if (customDownloadDirectory.exists()) {
                File file = new File(customDownloadDirectory, imgName);
                fos = new FileOutputStream(file);
                fos.write(bytes);
                fos.flush();
                fos.close();
                if (file != null) {
                    ContentValues values = new ContentValues();
                    values.put(MediaStore.Images.Media.TITLE, file.getName());
                    values.put(MediaStore.Images.Media.DISPLAY_NAME, file.getName());
                    values.put(MediaStore.Images.Media.DESCRIPTION, "");
                    values.put(MediaStore.Images.Media.MIME_TYPE, "image/gif");
                    values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis());
                    values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
                    values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());

                    ContentResolver contentResolver = context.getContentResolver();
                    contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

                    Toast.makeText(context, "Image saved to " + file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM