ImageUtil常用的显示图片方法,好东西留着别忘记了

public class ImageUtils {

   private static final int MAX_DECODE_PICTURE_SIZE = 1920 * 1440;
   public static boolean inNativeAllocAccessError = false;

   public static void setHeadImage(String imgurl, ImageView imageView) {
      ImageLoader.getInstance().displayImage(imgurl+"?imageView2/2/h/200", imageView,
            AppManager.headImgOptions);
   }

   public static void setImage(String imgurl, ImageView imageView) {
      ImageLoader.getInstance().displayImage(imgurl, imageView,
            AppManager.imgOptions);
   }

   public static void setImage(String imgurl, ImageView imageView,
         DisplayImageOptions options) {
      ImageLoader.getInstance().displayImage(imgurl, imageView, options);
   }

   /**
    * 等级
    * 
    * @param i
    * @param img
    */
   public static void setGrade(int i, ImageView img) {
      switch (i) {
      case 1:
         img.setImageResource(R.drawable.grade_iocn_1);
         break;
      case 2:
         img.setImageResource(R.drawable.grade_iocn_2);
         break;
      case 3:
         img.setImageResource(R.drawable.grade_iocn_3);
         break;
      case 4:
         img.setImageResource(R.drawable.grade_iocn_4);
         break;
      default:
         break;
      }
   }
   
   /**
    * 等级
    * 
    * @param i
    * @param img
    */
   public static void setGrade1(int i, ImageView img) {
      switch (i) {
      case 1:
         img.setImageResource(R.drawable.user_grade_1);
         break;
      case 2:
         img.setImageResource(R.drawable.user_grade_2);
         break;
      case 3:
         img.setImageResource(R.drawable.user_grade_3);
         break;
      case 4:
         img.setImageResource(R.drawable.user_grade_4);
         break;
      default:
         break;
      }
   }

   /**
    * 点赞
    * 
    * @param b
    * @param img
    */
   public static void setPraise(boolean b, ImageView img) {
      if (b) {
         img.setImageResource(R.drawable.praise_selected);
      } else {
         img.setImageResource(R.drawable.praise_normal);
      }
   }

   /**
    * 获取资源文件图片
    * 
    * @param context
    * @param id
    */
   public static Bitmap getBitmapRes(Context context, int id) {
      return BitmapFactory.decodeResource(context.getResources(), id);
   }

   /**
    * 获取资源文件图片
    * 重新绘制图片大小
    * @param context
    * @param id
    * @param w
    * @param h
    */
   public static Bitmap getBitmapRes(Context context,int id,int w,int h){
      Bitmap source = BitmapFactory.decodeResource(context.getResources(),id);
      Bitmap target = Bitmap.createBitmap(w, h, source.getConfig());
      Canvas canvas = new Canvas(target);
      canvas.drawBitmap(source, null, new Rect(0, 0, target.getWidth(), target.getHeight()), null);
      return target;
   }

   /**
    * 设置本地图片
    * 
    * @param imageId
    * @param imageView
    * @param isRound
    *            是否圆形
    */
   public static void setImgFromDrawable(int imageId, ImageView imageView,
         boolean isRound) {
      if (isRound) {
         DisplayImageOptions options = new DisplayImageOptions.Builder()
               .displayer(new RoundedBitmapDisplayer(50)) // 设置成圆角图片 弧度
               .build();
         ImageLoader.getInstance().displayImage("drawable://" + imageId,
               imageView, options);
      } else {
         ImageLoader.getInstance().displayImage("drawable://" + imageId,
               imageView);
      }

   }

   /**
    * 下载图片到本地
    * 
    * @param url
    */
   public static Bitmap loadImgInLocal(String url) {
      DisplayImageOptions options = new DisplayImageOptions.Builder()
            .cacheOnDisk(true) // 设置下载的图片是否缓存在SD卡中
            .build();
      return ImageLoader.getInstance().loadImageSync(url, options);
   }

   public static void setImage(String imgurl, ImageView imageView, int r) {
      DisplayImageOptions imgOptions = new DisplayImageOptions.Builder()
            .showImageOnLoading(r).showImageForEmptyUri(r)
            .showImageOnFail(r).cacheInMemory(false).cacheOnDisk(true)
            .build();
      ImageLoader.getInstance().displayImage(imgurl, imageView, imgOptions);
   }

   public static Bitmap getImageThumbnail(String imagePath, int width,
         int height) {
      Bitmap bitmap = null;
      BitmapFactory.Options options = new BitmapFactory.Options();
      options.inJustDecodeBounds = true;
      // 获取这个图片的宽和高,注意此处的bitmap为null
      bitmap = BitmapFactory.decodeFile(imagePath, options);
      options.inJustDecodeBounds = false; // 设为 false
      // 计算缩放比
      int h = options.outHeight;
      int w = options.outWidth;
      int beWidth = w / width;
      int beHeight = h / height;
      int be = 1;
      if (beWidth < beHeight) {
         be = beWidth;
      } else {
         be = beHeight;
      }
      if (be <= 0) {
         be = 1;
      }
      options.inSampleSize = be;
      // 重新读入图片,读取缩放后的bitmap,注意这次要把options.inJustDecodeBounds 设为 false
      bitmap = BitmapFactory.decodeFile(imagePath, options);
      // 利用ThumbnailUtils来创建缩略图,这里要指定要缩放哪个Bitmap对象
      bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
            ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
      return bitmap;
   }

   public static void setImage(Context context, String cacheUrl,
         String imgurl, ImageView imageView, int r) {
      boolean bool = false;
      if (!StringUitls.isEmpty(cacheUrl)) {
         final File avatarFile = new File(cacheUrl);
         if (avatarFile.exists()) {
            try {
               BitmapFactory.Options options = new BitmapFactory.Options();
               options.inSampleSize = 2;
               Bitmap bitmap = BitmapFactory.decodeFile(
                     avatarFile.getPath(), options);
               imageView.setImageBitmap(bitmap);
            } catch (Exception e1) {
               bool = true;
            }
         } else {
            bool = true;
         }
      } else {
         bool = true;
      }
      if (bool) {
         if (StringUitls.isEmpty(imgurl)) {
            imageView.setImageResource(r);
         } else {
            ImageLoader.getInstance().displayImage(imgurl, imageView);
         }
      }
   }

   /**
    * 旋转图片
    * 
    * @param srcPath
    * @param degrees
    * @param format
    * @param root
    * @param fileName
    * @return
    */
   public static boolean rotateCreateBitmap(String srcPath, int degrees,
         Bitmap.CompressFormat format, String root, String fileName) {
      Bitmap decodeFile = BitmapFactory.decodeFile(srcPath);
      if (decodeFile == null) {
         return false;
      }
      int width = decodeFile.getWidth();
      int height = decodeFile.getHeight();
      Matrix matrix = new Matrix();
      matrix.setRotate(degrees, width / 2.0F, height / 2.0F);
      Bitmap createBitmap = Bitmap.createBitmap(decodeFile, 0, 0, width,
            height, matrix, true);
      decodeFile.recycle();
      try {
         saveImageFile(createBitmap, 60, format, root, fileName);
         return true;
      } catch (Exception e) {
      }
      return false;
   }

   /**
    * 生成一张缩略图
    * 
    * @param bitmap
    * @param paramFloat
    * @return
    */
   public static Bitmap processBitmap(Bitmap bitmap, float paramFloat) {
      Assert.assertNotNull(bitmap);
      Bitmap resultBitmap = Bitmap.createBitmap(bitmap.getWidth(),
            bitmap.getHeight(), Bitmap.Config.ARGB_8888);
      Canvas canvas = new Canvas(resultBitmap);
      Paint paint = new Paint();
      Rect localRect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
      RectF rectF = new RectF(localRect);
      paint.setAntiAlias(true);
      paint.setDither(true);
      paint.setFilterBitmap(true);
      canvas.drawARGB(0, 0, 0, 0);
      paint.setColor(4144960);
      canvas.drawRoundRect(rectF, paramFloat, paramFloat, paint);
      paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
      canvas.drawBitmap(bitmap, localRect, localRect, paint);
      bitmap.recycle();
      return resultBitmap;
   }

   public static String getAbsoluteImagePath(Context context, Uri uri) {
      // can post image
      String[] proj = { MediaStore.Images.Media.DATA };
      Cursor cursor = context.getContentResolver().query(uri, proj, null,
            null, null);

      int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
      cursor.moveToFirst();

      return cursor.getString(column_index);
   }

   public static Bitmap getimageByImageLoad(String url) {
      return ImageLoader.getInstance().loadImageSync(url);
   }

   /**
    * 根据路径加载本地图片
    * 
    * @param srcPath
    * @return
    */
   public static Bitmap getimage(String srcPath) {
      BitmapFactory.Options newOpts = new BitmapFactory.Options();
      // 开始读入图片,此时把options.inJustDecodeBounds 设回true了
      newOpts.inJustDecodeBounds = true;
      Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此时返回bm为空

      newOpts.inJustDecodeBounds = false;
      int w = newOpts.outWidth;
      int h = newOpts.outHeight;
      // 现在主流手机比较多是800*480分辨率,所以高和宽我们设置为
      float hh = 800f;// 这里设置高度为800f
      float ww = 480f;// 这里设置宽度为480f
      // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
      int be = 1;// be=1表示不缩放
      if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
         be = (int) (newOpts.outWidth / ww);
      } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
         be = (int) (newOpts.outHeight / hh);
      }
      if (be <= 0)
         be = 1;
      newOpts.inSampleSize = be;// 设置缩放比例
      // 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
      return BitmapFactory.decodeFile(srcPath, newOpts);
      // bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
      // return compressImage(bitmap, kb);// 压缩好比例大小后再进行质量压缩
   }

   public static Bitmap comp(Bitmap image, int kb) {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
      if (baos.toByteArray().length / 1024 > 1024) {// 判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出
         baos.reset();// 重置baos即清空baos
         image.compress(Bitmap.CompressFormat.JPEG, 50, baos);// 这里压缩50%,把压缩后的数据存放到baos中
      }
      ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
      BitmapFactory.Options newOpts = new BitmapFactory.Options();
      // 开始读入图片,此时把options.inJustDecodeBounds 设回true了
      newOpts.inJustDecodeBounds = true;
      Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
      newOpts.inJustDecodeBounds = false;
      int w = newOpts.outWidth;
      int h = newOpts.outHeight;
      // 现在主流手机比较多是800*480分辨率,所以高和宽我们设置为
      float hh = 800f;// 这里设置高度为800f
      float ww = 480f;// 这里设置宽度为480f
      // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
      int be = 1;// be=1表示不缩放
      if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
         be = (int) (newOpts.outWidth / ww);
      } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
         be = (int) (newOpts.outHeight / hh);
      }
      if (be <= 0)
         be = 1;
      newOpts.inSampleSize = be;// 设置缩放比例
      // 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
      isBm = new ByteArrayInputStream(baos.toByteArray());
      bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
      return compressImage(bitmap, kb);// 压缩好比例大小后再进行质量压缩
   }

   /**
    * 缩小图片质量,保持到本地
    * 
    * @param bmp
    * @param file
    */
   public static void compressBmpToFile(Bitmap bmp, File file) {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      int options = 80;// 个人喜欢从80开始,
      bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
      while (baos.toByteArray().length / 1024 > 100) {
         baos.reset();
         options -= 10;
         bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
      }
      try {
         FileOutputStream fos = new FileOutputStream(file);
         fos.write(baos.toByteArray());
         fos.flush();
         fos.close();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   public static Bitmap compressImage(Bitmap image, Integer kb) {
      if (kb == null) {
         kb = 100;
      }
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
      int options = 100;
      while (baos.toByteArray().length / 1024 > kb) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
         baos.reset();// 重置baos即清空baos
         image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中
         options -= 10;// 每次都减少10
      }
      ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
      Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
      return bitmap;
   }

   public static InputStream getImageStream(String path) throws Exception {
      URL url = new URL(path);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setConnectTimeout(5 * 1000);
      conn.setRequestMethod("GET");
      if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
         return conn.getInputStream();
      }
      return null;
   }

   /**
    * 获取图片被旋转的角度
    * 
    * @param filePath
    * @return
    */
   public static int getBitmapDegrees(String filePath) {
      if (TextUtils.isEmpty(filePath)) {
         return 0;
      }
      if (!new File(filePath).exists()) {
         return 0;
      }
      ExifInterface exifInterface = null;
      try {

         if (Integer.valueOf(Build.VERSION.SDK).intValue() >= 5) {
            exifInterface = new ExifInterface(filePath);
            int attributeInt = -1;
            if (exifInterface != null) {
               attributeInt = exifInterface.getAttributeInt(
                     ExifInterface.TAG_ORIENTATION, -1);
            }

            if (attributeInt != -1) {
               switch (attributeInt) {
               case ExifInterface.ORIENTATION_FLIP_VERTICAL:
               case ExifInterface.ORIENTATION_TRANSPOSE:
               case ExifInterface.ORIENTATION_TRANSVERSE:
                  return 0;
               case ExifInterface.ORIENTATION_ROTATE_180:
                  return 180;
               case ExifInterface.ORIENTATION_ROTATE_90:
                  return 90;
               case ExifInterface.ORIENTATION_ROTATE_270:
                  return 270;
               default:
                  break;
               }
            }
         }
      } catch (IOException e) {

      } finally {
         exifInterface = null;
      }
      return 0;
   }

   /**
    * 得到指定路径图片的options
    * 
    * @param srcPath
    * @return Options {@link android.graphics.BitmapFactory.Options}
    */
   public final static BitmapFactory.Options getBitmapOptions(String srcPath) {
      BitmapFactory.Options options = new BitmapFactory.Options();
      options.inJustDecodeBounds = true;
      BitmapFactory.decodeFile(srcPath, options);
      return options;
   }

   /**
    * 压缩发送到服务器的图片
    * 
    * @param origPath
    *            原始图片路径
    * @param widthLimit
    *            图片宽度限制
    * @param heightLimit
    *            图片高度限制
    * @param format
    *            图片格式
    * @param quality
    *            图片压缩率
    * @param authorityDir
    *            图片目录
    * @param outPath
    *            图片详细目录
    * @return
    */
   public static boolean createThumbnailFromOrig(String origPath,
         int widthLimit, int heightLimit, Bitmap.CompressFormat format,
         int quality, String authorityDir, String outPath) {
      Bitmap bitmapThumbNail = extractThumbNail(origPath, widthLimit,
            heightLimit, false);
      if (bitmapThumbNail == null) {
         return false;
      }

      try {
         saveImageFile(bitmapThumbNail, quality, format, authorityDir,
               outPath);
         return true;
      } catch (IOException e) {

      }
      return false;
   }

   public static void saveImageFile(Bitmap bitmap, int quality,
         Bitmap.CompressFormat format, String authorityDir, String outPath)
         throws IOException {
      if (!TextUtils.isEmpty(authorityDir) && !TextUtils.isEmpty(outPath)) {
         File file = new File(authorityDir);
         if (!file.exists()) {
            file.mkdirs();
         }
         File outfile = new File(file, outPath);
         outfile.createNewFile();

         try {
            FileOutputStream outputStream = new FileOutputStream(outfile);
            bitmap.compress(format, quality, outputStream);
            outputStream.flush();
         } catch (Exception e) {
         }
      }
   }

   @TargetApi(Build.VERSION_CODES.HONEYCOMB)
   public static Bitmap extractThumbNail(final String path, final int width,
         final int height, final boolean crop) {
      Assert.assertTrue(path != null && !path.equals("") && height > 0
            && width > 0);

      BitmapFactory.Options options = new BitmapFactory.Options();

      try {
         options.inJustDecodeBounds = true;
         Bitmap tmp = BitmapFactory.decodeFile(path, options);
         if (tmp != null) {
            tmp.recycle();
            tmp = null;
         }

         final double beY = options.outHeight * 1.0 / height;
         final double beX = options.outWidth * 1.0 / width;
         options.inSampleSize = (int) (crop ? (beY > beX ? beX : beY)
               : (beY < beX ? beX : beY));
         if (options.inSampleSize <= 1) {
            options.inSampleSize = 1;
         }

         // NOTE: out of memory error
         while (options.outHeight * options.outWidth / options.inSampleSize > MAX_DECODE_PICTURE_SIZE) {
            options.inSampleSize++;
         }

         int newHeight = height;
         int newWidth = width;
         if (crop) {
            if (beY > beX) {
               newHeight = (int) (newWidth * 1.0 * options.outHeight / options.outWidth);
            } else {
               newWidth = (int) (newHeight * 1.0 * options.outWidth / options.outHeight);
            }
         } else {
            if (beY < beX) {
               newHeight = (int) (newWidth * 1.0 * options.outHeight / options.outWidth);
            } else {
               newWidth = (int) (newHeight * 1.0 * options.outWidth / options.outHeight);
            }
         }

         options.inJustDecodeBounds = false;
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            options.inMutable = true;
         }
         Bitmap bm = BitmapFactory.decodeFile(path, options);
         setInNativeAlloc(options);
         if (bm == null) {
            return null;
         }

         final Bitmap scale = Bitmap.createScaledBitmap(bm, newWidth,
               newHeight, true);
         if (scale != null) {
            bm.recycle();
            bm = scale;
         }

         if (crop) {
            final Bitmap cropped = Bitmap.createBitmap(bm,
                  (bm.getWidth() - width) >> 1,
                  (bm.getHeight() - height) >> 1, width, height);
            if (cropped == null) {
               return bm;
            }

            bm.recycle();
            bm = cropped;

         }
         return bm;

      } catch (final OutOfMemoryError e) {

         options = null;
      }

      return null;
   }

   public static void setInNativeAlloc(BitmapFactory.Options options) {
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH
            && !inNativeAllocAccessError) {
         try {
            BitmapFactory.Options.class.getField("inNativeAlloc")
                  .setBoolean(options, true);
            return;
         } catch (Exception e) {
            inNativeAllocAccessError = true;
         }
      }
   }

   /**
    * 
    * @param context
    * @param id
    * @return
    */
   public static Drawable getDrawables(Context context, int id) {
      Drawable drawable = context.getResources().getDrawable(id);
      drawable.setBounds(0, 0, drawable.getMinimumWidth(),
            drawable.getMinimumHeight());

      return drawable;
   }
   
   public static int calculateInSampleSize(BitmapFactory.Options options,
         int reqWidth, int reqHeight) {
      final int height = options.outHeight;
      final int width = options.outWidth;
      int inSampleSize = 1;

      if (height > reqHeight || width > reqWidth) {
         final int heightRatio = Math.round((float) height
               / (float) reqHeight);
         final int widthRatio = Math.round((float) width / (float) reqWidth);
         inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
      }
      return inSampleSize;
   }

   // 根据路径获得图片并压缩,返回bitmap用于显示
   public static Bitmap getSmallBitmap(String filePath) {
      final BitmapFactory.Options options = new BitmapFactory.Options();
      options.inJustDecodeBounds = true;
      BitmapFactory.decodeFile(filePath, options);

      // Calculate inSampleSize
      options.inSampleSize = calculateInSampleSize(options, 480, 800);

      // Decode bitmap with inSampleSize set
      options.inJustDecodeBounds = false;

      return BitmapFactory.decodeFile(filePath, options);
   }

   // 把bitmap转换成String
   public static String bitmapToString(String filePath) {

      Bitmap bm = getSmallBitmap(filePath);
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      bm.compress(Bitmap.CompressFormat.JPEG, 40, baos);
      byte[] b = baos.toByteArray();
      return Base64.encodeToString(b, Base64.DEFAULT);
   }
   
   public static int readPictureDegree(String path) {  
       int degree  = 0;  
       try {  
           ExifInterface exifInterface = new ExifInterface(path);  
           int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);  
           switch (orientation) {  
               case ExifInterface.ORIENTATION_ROTATE_90:  
                   degree = 90;  
                   break;  
               case ExifInterface.ORIENTATION_ROTATE_180:  
                   degree = 180;  
                   break;  
               case ExifInterface.ORIENTATION_ROTATE_270:  
                   degree = 270;  
                   break;  
           }  
       } catch (IOException e) {  
           e.printStackTrace();  
       }  
       return degree;  
   }  
   
   public static Bitmap rotaingImageView(int angle , Bitmap bitmap) {  
       //旋转图片 动作  
       Matrix matrix = new Matrix();;  
       matrix.postRotate(angle);  
       System.out.println("angle2=" + angle);  
       // 创建新的图片  
       Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,  
               bitmap.getWidth(), bitmap.getHeight(), matrix, true);  
       return resizedBitmap;  
   }  
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值