[Java] 根据URL抓取并生成缩略图的Java代码 →→→→→进入此内容的聊天室

来自 , 2020-11-13, 写在 Java, 查看 119 次.
URL http://www.code666.cn/view/eccd9f7d
  1. public static Bitmap loadImageFromUrl(String url, int sc) {
  2.         URL m;
  3.         InputStream i = null;
  4.         BufferedInputStream bis = null;
  5.         ByteArrayOutputStream out = null;
  6.         byte isBuffer[] = new byte[1024];
  7.         if (url == null)
  8.             return null;
  9.         try {
  10.             m = new URL(url);
  11.             i = (InputStream) m.getContent();
  12.  
  13.             bis = new BufferedInputStream(i, 1024 * 4);
  14.             out = new ByteArrayOutputStream();
  15.             int len = 0;
  16.             while ((len = bis.read(isBuffer)) != -1) {
  17.                 out.write(isBuffer, 0, len);
  18.             }
  19.             out.close();
  20.             bis.close();
  21.         } catch (MalformedURLException e1) {
  22.             e1.printStackTrace();
  23.             return null;
  24.         } catch (IOException e) {
  25.             e.printStackTrace();
  26.         }
  27.         if (out == null)
  28.             return null;
  29.         byte[] data = out.toByteArray();
  30.         BitmapFactory.Options options = new BitmapFactory.Options();
  31.         options.inJustDecodeBounds = true;
  32.         BitmapFactory.decodeByteArray(data, 0, data.length, options);
  33.         options.inJustDecodeBounds = false;
  34.         int be = (int) (options.outHeight / (float) sc);
  35.         if (be <= 0) {
  36.             be = 1;
  37.         } else if (be > 3) {
  38.             be = 3;
  39.         }
  40.         options.inSampleSize = be;
  41.         Bitmap bmp = null;
  42.         try {
  43.             bmp = BitmapFactory.decodeByteArray(data, 0, data.length, options); // 返回缩略图
  44.         } catch (OutOfMemoryError e) {
  45.             // TODO: handle exception
  46.             System.gc();
  47.             bmp = null;
  48.         }
  49.         return bmp;
  50.     }
  51. //java/6811

回复 "根据URL抓取并生成缩略图的Java代码"

这儿你可以回复上面这条便签

captcha