Glide加载图片并保存到本地返回file,bitmap

不废话,直接上代码

  1. import android.content.Context;  
  2. import android.content.Intent;  
  3. import android.graphics.Bitmap;  
  4. import android.net.Uri;  
  5.   
  6. import com.baguanv.jinba.utils.Const;  
  7. import com.bumptech.glide.Glide;  
  8. import com.bumptech.glide.request.target.Target;  
  9.   
  10. import java.io.File;  
  11. import java.io.FileNotFoundException;  
  12. import java.io.FileOutputStream;  
  13. import java.io.IOException;  
  14.   
  15. /** 
  16.  * 图片下载 
  17.  *  
  18.  */  
  19. public class DownLoadImageService implements Runnable {  
  20.     private String url;  
  21.     private Context context;  
  22.     private ImageDownLoadCallBack callBack;  
  23.     private File currentFile;  
  24.     public DownLoadImageService(Context context, String url, ImageDownLoadCallBack callBack) {  
  25.         this.url = url;  
  26.         this.callBack = callBack;  
  27.         this.context = context;  
  28.     }  
  29.   
  30.     @Override  
  31.     public void run() {  
  32.         File file = null;  
  33.         Bitmap bitmap = null;  
  34.         try {  
  35. //            file = Glide.with(context)  
  36. //                    .load(url)  
  37. //                    .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)  
  38. //                    .get();  
  39.             bitmap = Glide.with(context)  
  40.                     .load(url)  
  41.                     .asBitmap()  
  42.                     .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)  
  43.                     .get();  
  44.             if (bitmap != null){  
  45.                 // 在这里执行图片保存方法  
  46.                 saveImageToGallery(context,bitmap);  
  47.             }  
  48.         } catch (Exception e) {  
  49.             e.printStackTrace();  
  50.         } finally {  
  51. //            if (file != null) {  
  52. //                callBack.onDownLoadSuccess(file);  
  53. //            } else {  
  54. //                callBack.onDownLoadFailed();  
  55. //            }  
  56.             if (bitmap != null && currentFile.exists()) {  
  57.                 callBack.onDownLoadSuccess(bitmap);  
  58.             } else {  
  59.                 callBack.onDownLoadFailed();  
  60.             }  
  61.         }  
  62.     }  
  63.   
  64.     public void saveImageToGallery(Context context, Bitmap bmp) {  
  65.         // 首先保存图片  
  66.         String File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();//注意小米手机必须这样获得public绝对路径  
  67.         String fileName = ”新建文件夹”;  
  68.        File appDir = new File(file ,fileName);  
  69.         if (!appDir.exists()) {  
  70.             appDir.mkdirs();  
  71.         }  
  72.         String fileName = System.currentTimeMillis() + ”.jpg”;  
  73.         currentFile = new File(appDir, fileName);  
  74.   
  75.         FileOutputStream fos = null;  
  76.         try {  
  77.             fos = new FileOutputStream(currentFile);  
  78.             bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);  
  79.             fos.flush();  
  80.         } catch (FileNotFoundException e) {  
  81.             e.printStackTrace();  
  82.         } catch (IOException e) {  
  83.             e.printStackTrace();  
  84.         } finally {  
  85.             try {  
  86.                 if (fos != null) {  
  87.                     fos.close();  
  88.                 }  
  89.             } catch (IOException e) {  
  90.                 e.printStackTrace();  
  91.             }  
  92.         }  
  93.   
  94.         // 其次把文件插入到系统图库  
  95. //        try {  
  96. //            MediaStore.Images.Media.insertImage(context.getContentResolver(),  
  97. //                    currentFile.getAbsolutePath(), fileName, null);  
  98. //        } catch (FileNotFoundException e) {  
  99. //            e.printStackTrace();  
  100. //        }  
  101.   
  102.         // 最后通知图库更新  
  103.         context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,  
  104.                 Uri.fromFile(new File(currentFile.getPath()))));  
  105.     }  
  106. }  
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;

import com.baguanv.jinba.utils.Const;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 图片下载
 * 
 */
public class DownLoadImageService implements Runnable {
    private String url;
    private Context context;
    private ImageDownLoadCallBack callBack;
    private File currentFile;
    public DownLoadImageService(Context context, String url, ImageDownLoadCallBack callBack) {
        this.url = url;
        this.callBack = callBack;
        this.context = context;
    }

    @Override
    public void run() {
        File file = null;
        Bitmap bitmap = null;
        try {
//            file = Glide.with(context)
//                    .load(url)
//                    .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
//                    .get();
            bitmap = Glide.with(context)
                    .load(url)
                    .asBitmap()
                    .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                    .get();
            if (bitmap != null){
                // 在这里执行图片保存方法
                saveImageToGallery(context,bitmap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//            if (file != null) {
//                callBack.onDownLoadSuccess(file);
//            } else {
//                callBack.onDownLoadFailed();
//            }
            if (bitmap != null && currentFile.exists()) {
                callBack.onDownLoadSuccess(bitmap);
            } else {
                callBack.onDownLoadFailed();
            }
        }
    }

    public void saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        String File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();//注意小米手机必须这样获得public绝对路径
        String fileName = "新建文件夹";
       File appDir = new File(file ,fileName);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        currentFile = new File(appDir, fileName);

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(currentFile);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 其次把文件插入到系统图库
//        try {
//            MediaStore.Images.Media.insertImage(context.getContentResolver(),
//                    currentFile.getAbsolutePath(), fileName, null);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }

        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.fromFile(new File(currentFile.getPath()))));
    }
}

  1. public interface ImageDownLoadCallBack {  
  2.     void onDownLoadSuccess(File file);  
  3.     void onDownLoadSuccess(Bitmap bitmap);  
  4.   
  5.     void onDownLoadFailed();  
  6. }  
public interface ImageDownLoadCallBack {
    void onDownLoadSuccess(File file);
    void onDownLoadSuccess(Bitmap bitmap);

    void onDownLoadFailed();
}

  1. /** 
  2.      * 启动图片下载线程 
  3.      */  
  4.     private void onDownLoad(String url) {  
  5.         DownLoadImageService service = new DownLoadImageService(getApplicationContext(),  
  6.                 url,  
  7.                 new ImageDownLoadCallBack() {  
  8.   
  9.                     @Override  
  10.                     public void onDownLoadSuccess(File file) {  
  11.                     }  
  12.                     @Override  
  13.                     public void onDownLoadSuccess(Bitmap bitmap) {  
  14.                         // 在这里执行图片保存方法  
  15.                         Message message = new Message();  
  16.                         message.what = MSG_VISIBLE;  
  17.                         handler.sendMessageDelayed(message, delayTime);  
  18.                     }  
  19.   
  20.                     @Override  
  21.                     public void onDownLoadFailed() {  
  22.                         // 图片保存失败  
  23.                         Message message = new Message();  
  24.                         message.what = MSG_ERROR;  
  25.                         handler.sendMessageDelayed(message, delayTime);  
  26.                     }  
  27.                 });  
  28.         //启动图片下载线程  
  29.         new Thread(service).start();  
  30.     }  
/**
     * 启动图片下载线程
     */
    private void onDownLoad(String url) {
        DownLoadImageService service = new DownLoadImageService(getApplicationContext(),
                url,
                new ImageDownLoadCallBack() {

                    @Override
                    public void onDownLoadSuccess(File file) {
                    }
                    @Override
                    public void onDownLoadSuccess(Bitmap bitmap) {
                        // 在这里执行图片保存方法
                        Message message = new Message();
                        message.what = MSG_VISIBLE;
                        handler.sendMessageDelayed(message, delayTime);
                    }

                    @Override
                    public void onDownLoadFailed() {
                        // 图片保存失败
                        Message message = new Message();
                        message.what = MSG_ERROR;
                        handler.sendMessageDelayed(message, delayTime);
                    }
                });
        //启动图片下载线程
        new Thread(service).start();
    }


  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要获取 GIF 图片的第一帧并保存到本地,可以使用 Glide 或者 BitmapFactory 进行处理,然后将 Bitmap 保存图片文件。 使用 Glide: ```java Glide.with(context) .asBitmap() .load(gifUrl) .diskCacheStrategy(DiskCacheStrategy.DATA) .addListener(new RequestListener<Bitmap>() { @Override public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) { return false; } @Override public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) { // 处理第一帧图片 saveBitmapToFile(resource, filePath); return false; } }) .submit(); ``` 使用 BitmapFactory: ```java // 获取 GIF 图片的字节数组 byte[] gifBytes = getGifBytes(gifUrl); if (gifBytes != null) { // 解码字节数组,获取第一帧图片 Bitmap bitmap = BitmapFactory.decodeByteArray(gifBytes, 0, gifBytes.length, null); // 处理第一帧图片 saveBitmapToFile(bitmap, filePath); } ``` 其中,`getGifBytes` 方法可以使用网络请求等方式获取 GIF 图片的字节数组,`saveBitmapToFile` 方法用于将 Bitmap 保存图片文件: ```java public static void saveBitmapToFile(Bitmap bitmap, String filePath) { if (bitmap == null || TextUtils.isEmpty(filePath)) { return; } File file = new File(filePath); if (file.exists()) { file.delete(); } try { FileOutputStream fos = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.flush(); fos.close(); } catch (IOException e) { e.printStackTrace(); } } ``` 这里将 Bitmap 以 PNG 格式保存,可以根据需要修改为 JPG 等其他格式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值