android工具类----(从网络获取图片以及异步加载图片)

本文介绍了一个用于从网络获取图片并将其保存到本地的工具类,包括图片路径处理、下载、保存以及异步加载功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. import java.io.ByteArrayOutputStream; 
  2. import java.io.File; 
  3. import java.io.FileOutputStream; 
  4. import java.io.IOException; 
  5. import java.io.InputStream; 
  6. import java.net.HttpURLConnection; 
  7. import java.net.URL; 
  8. import android.graphics.Bitmap; 
  9. import android.graphics.BitmapFactory;
  10. import android.os.AsyncTask; 
  11. import android.os.Environment; 
  12. import android.util.Log; 
  13. import android.widget.ImageView; 
  14.  
  15. /**
  16. * 处理图片的工具类
  17. */ 
  18. public class ImageUtils { 
  19.  
  20.     /**
  21.      * 图片基准路径
  22.      */ 
  23.     private static final String BASE_SDCARD_IMAGES = "/mnt/sdcard/demo/images/"
  24.  
  25.     private static final String TAG = "ImageUtils"
  26.  
  27.     /**
  28.      * 判断文件是否存在
  29.      *
  30.      * @param 文件在本地的完整名
  31.      * @return
  32.      */ 
  33.     private static boolean judgeExists(String fullName) { 
  34.  
  35.         File file = new File(fullName); 
  36.  
  37.         return file.exists(); 
  38.     } 
  39.  
  40.     /**
  41.      * 获取最后的‘/’后的文件名
  42.      *
  43.      * @param name
  44.      * @return
  45.      */ 
  46.     private static String getLastName(String name) { 
  47.         int lastIndexOf = 0
  48.         try
  49.             lastIndexOf = name.lastIndexOf('/'); 
  50.         } catch (Exception e) { 
  51.             e.printStackTrace(); 
  52.         } 
  53.         return !name.equals("") ? name.substring(lastIndexOf + 1) : ""
  54.     } 
  55.  
  56.     /**
  57.      * 拼接一个完整的本地文件名
  58.      * @param 文件的网络路径
  59.      * @return
  60.      */ 
  61.     private static String getImageFullName(String name) { 
  62.         return BASE_SDCARD_IMAGES + getLastName(name); 
  63.     } 
  64.  
  65.     /**
  66.      * 通过该网络路径获取Bitmap
  67.      * @param 该图片的网络路径
  68.      */ 
  69.     public static Bitmap getBitmap(String urlPath) { 
  70.  
  71.         Bitmap bitmap = null
  72.         String fullName = getImageFullName(urlPath); 
  73.         if (ImageUtils.judgeExists(fullName)) { 
  74.             /* 存在就直接使用 */ 
  75.             Log.e(TAG, "使用了sdcard里的图片"); 
  76.             bitmap = BitmapFactory.decodeFile(fullName); 
  77.         } else
  78.             /* 去下载图片,下载完成之后返回该对象 */ 
  79.             Log.e(TAG, "去下载了图片"); 
  80.             bitmap = downloadAndSaveBitmap(urlPath, fullName); 
  81.         } 
  82.         return bitmap; 
  83.     } 
  84.  
  85.     /**
  86.      * 下载保存图片
  87.      *
  88.      * @param urlPath
  89.      *            下载路径
  90.      * @param fullName
  91.      *            文件保存路径+文件名
  92.      * @return
  93.      */ 
  94.     private static Bitmap downloadAndSaveBitmap(String urlPath, String fullName) { 
  95.  
  96.         Bitmap bitmap = downloadImage(urlPath); 
  97.  
  98.         /* 首先判断是否挂载了sdcard */ 
  99.         if (<span style="font-family: Arial, Helvetica, sans-serif;">Environment.MEDIA_MOUNTED.equals(</span><span style="font-family: Arial, Helvetica, sans-serif;">Environment.getExternalStorageState())) {</span> 
  100.  
  101.             if (bitmap != null) { 
  102.  
  103.                 saveBitmap(fullName, bitmap); 
  104.  
  105.             } 
  106.         } else
  107.             Log.e(TAG, "没有sdcard无法保存图片"); 
  108.         } 
  109.  
  110.         return bitmap; 
  111.     } 
  112.  
  113.     /**
  114.      * 保存图片
  115.      *
  116.      * @param fullName
  117.      * @param bitmap
  118.      */ 
  119.     private static void saveBitmap(String fullName, Bitmap bitmap) { 
  120.  
  121.         if (bitmap != null) { 
  122.  
  123.             try
  124.                 File file = new File(fullName); 
  125.                 if (!file.exists()) { 
  126.                     creatFolder(fullName); 
  127.                     file.createNewFile(); 
  128.                 } 
  129.                 FileOutputStream fos = new FileOutputStream(file); 
  130.                 bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); 
  131.                 fos.flush(); 
  132.             } catch (IOException e) { 
  133.                 e.printStackTrace(); 
  134.                 Log.e(TAG, "图片保存失败,异常信息是:" + e.toString()); 
  135.             } 
  136.         } else
  137.             Log.e(TAG, "没有下载成功图片,无法保存"); 
  138.         } 
  139.     } 
  140.  
  141.     /**
  142.      * 创建保存文件的文件夹
  143.      *
  144.      * @param fullName
  145.      *            带文件名的文件路径
  146.      * @return
  147.      */ 
  148.     private static void creatFolder(String fullName) { 
  149.         if (getLastName(fullName).contains(".")) { 
  150.             String newFilePath = fullName.substring(0, fullName 
  151.                     .lastIndexOf('/')); 
  152.             File file = new File(newFilePath); 
  153.             file.mkdirs(); 
  154.         } 
  155.     } 
  156.  
  157.     /**
  158.      * 下载图片
  159.      *
  160.      * @param urlPath
  161.      * @return
  162.      */ 
  163.     private static Bitmap downloadImage(String urlPath) { 
  164.  
  165.         try
  166.             byte[] byteData = getImageByte(urlPath); 
  167.             if (byteData == null) { 
  168.                 Log.e(TAG, "没有得到图片的byte,问题可能是path:" + urlPath); 
  169.                 return null
  170.             } 
  171.             int len = byteData.length; 
  172.  
  173.             BitmapFactory.Options options = new BitmapFactory.Options(); 
  174.             options.inPreferredConfig = Bitmap.Config.RGB_565; 
  175.             options.inPurgeable = true
  176.             options.inInputShareable = true
  177.             options.inJustDecodeBounds = false
  178.             if (len > 200000) {// 大于200K的进行压缩处理 
  179.                 options.inSampleSize = 2
  180.             } 
  181.  
  182.             return BitmapFactory.decodeByteArray(byteData, 0, len); 
  183.         } catch (Exception e) { 
  184.             e.printStackTrace(); 
  185.             Log.e(TAG, "图片下载失败,异常信息是:" + e.toString()); 
  186.             return null
  187.         } 
  188.     } 
  189.  
  190.     /**
  191.      * 获取图片的byte数组
  192.      *
  193.      * @param urlPath
  194.      * @return
  195.      */ 
  196.     private static byte[] getImageByte(String urlPath) { 
  197.         InputStream in = null
  198.         byte[] result = null
  199.         try
  200.             URL url = new URL(urlPath); 
  201.             HttpURLConnection httpURLconnection = (HttpURLConnection) url 
  202.                     .openConnection(); 
  203.             httpURLconnection.setDoInput(true); 
  204.             httpURLconnection.connect(); 
  205.             if (httpURLconnection.getResponseCode() == 200) { 
  206.                 in = httpURLconnection.getInputStream(); 
  207.                 result = readInputStream(in); 
  208.                 in.close(); 
  209.             } else
  210.                 Log 
  211.                         .e(TAG, "下载图片失败,状态码是:" 
  212.                                 + httpURLconnection.getResponseCode()); 
  213.             } 
  214.         } catch (Exception e) { 
  215.             Log.e(TAG, "下载图片失败,原因是:" + e.toString()); 
  216.             e.printStackTrace(); 
  217.         } finally
  218.             Log.e(TAG, "下载图片失败!"); 
  219.             if (in != null) { 
  220.                 try
  221.                     in.close(); 
  222.                 } catch (IOException e) { 
  223.                     e.printStackTrace(); 
  224.                 } 
  225.             } 
  226.         } 
  227.         return result; 
  228.     } 
  229.  
  230.     /**
  231.      * 将输入流转为byte数组
  232.      *
  233.      * @param in
  234.      * @return
  235.      * @throws Exception
  236.      */ 
  237.     private static byte[] readInputStream(InputStream in) throws Exception { 
  238.  
  239.         ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
  240.         byte[] buffer = new byte[1024]; 
  241.         int len = -1
  242.         while ((len = in.read(buffer)) != -1) { 
  243.             baos.write(buffer, 0, len); 
  244.         } 
  245.         baos.close(); 
  246.         in.close(); 
  247.         return baos.toByteArray(); 
  248.  
  249.     } 
  250.  
  251.     /**
  252.      * 此方法用来异步加载图片
  253.      * @param imageview
  254.      * @param path
  255.      */ 
  256.     public static void downloadAsyncTask(final ImageView imageview, 
  257.             final String path) { 
  258.         new AsyncTask<String, Void, Bitmap>() { 
  259.  
  260.             @Override 
  261.             protected Bitmap doInBackground(String... params) { 
  262.                 return getBitmap(path); 
  263.             } 
  264.  
  265.             @Override 
  266.             protected void onPostExecute(Bitmap result) { 
  267.                 super.onPostExecute(result); 
  268.                 if (result != null && imageview != null) { 
  269.                     imageview.setImageBitmap(result); 
  270.                 } else
  271.                     Log.e(TAG, "在downloadAsyncTask里异步加载图片失败!"); 
  272.                 } 
  273.             } 
  274.  
  275.         }.execute(new String[] {}); 
  276.  
  277.     } 
  278.  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值