java - 如何从url下载gif图像并保存到android中的存储

标签 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 图片已下载并保持静态

最佳答案

This snippet will help you to download gif using GLIDE

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

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

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

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

关于java - 如何从url下载gif图像并保存到android中的存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53956550/

相关文章:

android - Android中如何获取TextView的首字母?

c - 我的功能是以不同的方式将 PGM 图像文件复制到 PPM

java - Java中将文本数据处理为图像对象的最有效方法?

java - 如何同时打开前置摄像头和后置摄像头?

java - NotificationListenerService : NullPointerException on getActiveNotifications

java - 为什么JPanel的paintComponent(Graphics g)不运行?

android - 使用 Google Firestore(加上 Google Stack)跨 iOS 和 Android 制作 Unity 移动游戏

android - 未找到连接的设备;请连接设备

jquery - 如何更改图像 onclick javascript 函数?

java - 具有多个实体的 JPA 连接表