图片相关处理类BitmapUtil

前端之家收集整理的这篇文章主要介绍了图片相关处理类BitmapUtil前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. public class BitmapUtils {
  2. /**
  3. * 获取网络图片资源
  4. * @param url
  5. * @return
  6. */
  7. public static Bitmap getHttpBitmap(String url){
  8. URL myFileURL;
  9. Bitmap bitmap=null;
  10. try{
  11. myFileURL = new URL(url);
  12. //获得连接
  13. HttpURLConnection conn=(HttpURLConnection)myFileURL.openConnection();
  14. //设置超时时间为6000毫秒,conn.setConnectionTiem(0);表示没有时间限制
  15. conn.setConnectTimeout(6000);
  16. //连接设置获得数据流
  17. conn.setDoInput(true);
  18. //不使用缓存
  19. conn.setUseCaches(false);
  20. //这句可有可无,没有影响
  21. //conn.connect();
  22. //得到数据流
  23. InputStream is = conn.getInputStream();
  24. //解析得到图片
  25. bitmap = BitmapFactory.decodeStream(is);
  26. //关闭数据流
  27. is.close();
  28. }catch(Exception e){
  29. e.printStackTrace();
  30. }
  31. return bitmap;
  32. }
  33. /**
  34.  * 以最省内存的方式读取本地资源的<a href="/tag/tupian/" target="_blank" class="keywords">图片</a>
  35.  * @param context
  36.  * @param resId
  37.  * @return
  38.  */  
  39.  public static Bitmap readBitMap(Context context,int resId){  
  40.      BitmapFactory.Options opt = new BitmapFactory.Options();  
  41.      opt.inPreferredConfig = Bitmap.Config.RGB_565;   
  42.      opt.inPurgeable = true;  
  43.      opt.inInputShareable = true;  
  44.      //<a href="/tag/huoqu/" target="_blank" class="keywords">获取</a>资源<a href="/tag/tupian/" target="_blank" class="keywords">图片</a>  
  45.      InputStream is = context.getResources().openRawResource(resId); 
  46.      return BitmapFactory.decodeStream(is,null,opt);  
  47.   }
  48. /**
  49.  * 通过传入Path和ImageView加载相应的<a href="/tag/tupian/" target="_blank" class="keywords">图片</a>
  50.  * 对<a href="/tag/tupian/" target="_blank" class="keywords">图片</a>加载的优化
  51.  * @param imageView
  52.  */
  53. public static void loadPicture(ImageView imageView,String Path){
  54.     int reqWidth = imageView.getWidth();
  55.     int reqHeight = imageView.getHeight();
  56.     Bitmap bitmap = decodeSampledBitmapFromFile(Path,reqWidth,reqHeight);
  57.     if (bitmap != null){
  58.         imageView.setImageBitmap(bitmap);
  59.     }
  60. }
  61. public static Bitmap decodeSampledBitmapFromFile(String strPath,int reqWidth,int reqHeight) {   
  62.     // 第一次解析将inJustDecodeBounds设置为true,来<a href="/tag/huoqu/" target="_blank" class="keywords">获取</a><a href="/tag/tupian/" target="_blank" class="keywords">图片</a>大小   
  63.     final BitmapFactory.Options options = new BitmapFactory.Options();   
  64.     options.inJustDecodeBounds = true;   
  65.     BitmapFactory.decodeFile(strPath,options);
  66.     // <a href="/tag/diaoyong/" target="_blank" class="keywords">调用</a>上面定义的<a href="/tag/fangfa/" target="_blank" class="keywords">方法</a>计算inSampleSize值   
  67.     options.inSampleSize = calculateInSampleSize(options,reqHeight);   
  68.     // 使用<a href="/tag/huoqu/" target="_blank" class="keywords">获取</a>到的inSampleSize值再次解析<a href="/tag/tupian/" target="_blank" class="keywords">图片</a>   
  69.     options.inJustDecodeBounds = false;   
  70.     return BitmapFactory.decodeFile(strPath,options);   
  71. }
  72. public static int calculateInSampleSize(BitmapFactory.Options options,int reqHeight) {   
  73.     // 源<a href="/tag/tupian/" target="_blank" class="keywords">图片</a>的高度和宽度   
  74.     final int height = options.outHeight;   
  75.     final int width = options.outWidth;   
  76.     int inSampleSize = 1;   
  77.     if (height > reqHeight || width > reqWidth) {   
  78.         // 计算出实际宽高和目标宽高的比率   
  79.         final int heightRatio = Math.round((float) height / (float) reqHeight);   
  80.         final int widthRatio = Math.round((float) width / (float) reqWidth);   
  81.         // 选择宽和高中最小的比率作为inSampleSize的值,这样可以保证最终<a href="/tag/tupian/" target="_blank" class="keywords">图片</a>的宽和高   
  82.         // 一定都会大于等于目标的宽和高。   
  83.         inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;   
  84.     }   
  85.     return inSampleSize;   
  86. }
  87.  /**
  88.  *保存图片到文件
  89.  */
  90. public static File saveBitmapToFile(Bitmap bitmap) {
  91.     //如果相等的话表示当前的sdcard挂载在手机上并且是可用的  
  92.     if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){  
  93.         String storePath = Environment.getExternalStorageDirectory().toString() + "/yingzhidao/"+"header.jpg";
  94.         File file = new File(storePath);
  95.         if (!file.exists()){
  96.             file.mkdir();
  97.         }
  98.         try {
  99.             BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
  100.             bitmap.compress(Bitmap.CompressFormat.PNG,100,bos);
  101.             bos.flush();
  102.             bos.close();
  103.         } catch (IOException e) {
  104.             e.printStackTrace();
  105.         }
  106.         return file;
  107.     }
  108.     return null;
  109. }
  110. /**
  111.  * 压缩图片到制定大小
  112.  * @param bitmap
  113.  * @param size
  114.  * @return
  115.  */
  116. public static Bitmap imageZoom(Bitmap bitmap,double size) {
  117.     Bitmap targetBitmap = null;
  118.     targetBitmap = bitmap;
  119.     //图片允许最大空间   单位:KB
  120.     double maxSize =size;
  121.     //将bitmap放至数组中,意在bitmap的大小(与实际读取的原文件要大)
  122.     ByteArrayOutputStream baos = new ByteArrayOutputStream();
  123.     targetBitmap.compress(Bitmap.CompressFormat.JPEG,baos);
  124.     byte[] b = baos.toByteArray();
  125.     //将字节换成KB
  126.     double mid = b.length/1024;
  127.     //判断bitmap占用空间是否大于允许最大空间  如果大于则压缩 小于则不压缩
  128.     if (mid > maxSize) {
  129.         //<a href="/tag/huoqu/" target="_blank" class="keywords">获取</a>bitmap大小 是允许最大大小的多少倍
  130.         double i = mid / maxSize;
  131.         //开始压缩  此处用到平方根 将宽带和高度压缩掉对应的平方根倍 (1.保持刻度和高度和原bitmap比率一致,压缩后也达到了最大大小占用空间的大小)
  132.         targetBitmap = zoomImage(targetBitmap,targetBitmap.getWidth() / Math.sqrt(i),targetBitmap.getHeight() / Math.sqrt(i));
  133.     }
  134.     return targetBitmap;
  135. }
  136. public static Bitmap zoomImage(Bitmap bgimage,double newWidth,double newHeight) {
  137.     // <a href="/tag/huoqu/" target="_blank" class="keywords">获取</a>这个<a href="/tag/tupian/" target="_blank" class="keywords">图片</a>的宽和高
  138.     float width = bgimage.getWidth();
  139.     float height = bgimage.getHeight();
  140.     // 创建操作<a href="/tag/tupian/" target="_blank" class="keywords">图片</a>用的matrix对象
  141.     Matrix matrix = new Matrix();
  142.     // 计算宽高缩放率
  143.     float scaleWidth = ((float) newWidth) / width;
  144.     float scaleHeight = ((float) newHeight) / height;
  145.     // 缩放<a href="/tag/tupian/" target="_blank" class="keywords">图片</a>动作
  146.     matrix.postScale(scaleWidth,scaleHeight);
  147.     Bitmap bitmap = Bitmap.createBitmap(bgimage,(int) width,(int) height,matrix,true);
  148.     return bitmap;
  149. }
  150. /**
  151.  *为<a href="/tag/tupian/" target="_blank" class="keywords">图片</a><a href="/tag/tianjia/" target="_blank" class="keywords">添加</a>水印
  152.  */
  153. public static Bitmap drawTextToBitmap(Context gContext,int gResId,String text) {
  154.     Resources resources = gContext.getResources();
  155.     // float scale = resources.getDisplayMetrics().density;
  156.     Bitmap bitmap =
  157.             BitmapFactory.decodeResource(resources,gResId);
  158.     android.graphics.Bitmap.Config bitmapConfig =
  159.             bitmap.getConfig();
  160.     // set default bitmap config if none
  161.     if(bitmapConfig == null) {
  162.         bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
  163.     }
  164.     // resource bitmaps are imutable,// so we need to convert it to mutable one
  165.     bitmap = bitmap.copy(bitmapConfig,true);
  166.     int height = bitmap.getHeight();
  167.     int width = bitmap.getWidth();
  168.     // new antialised Paint
  169.     Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
  170.     // text color - #3D3D3D
  171.     paint.setColor(Color.rgb(255,255,255));
  172.     // text size in pixels
  173.     paint.setTextSize(32);
  174.     // text shadow
  175.     // paint.setShadowLayer(1f,0f,1f,Color.WHITE);
  176.     // draw text to the Canvas center
  177.     Rect bounds = new Rect();
  178.     paint.getTextBounds(text,text.length(),bounds);
  179.     Log.i("NEC","text width:"+bounds.width());
  180.     Log.i("NEC","text high:" + bounds.height());
  181.     int targetWidth = bounds.width()+40;
  182.     Matrix matrix = new Matrix();
  183.     float scaleWidth = ((float) targetWidth) / width;
  184.     float scaleHeight = ((float) height) / height;
  185.     matrix.postScale(scaleWidth,scaleHeight);
  186.     Bitmap scaleBitmap = Bitmap.createBitmap(bitmap,width,height,true);
  187.     int x = (scaleBitmap.getWidth() - bounds.width())/2;
  188.     int y = (scaleBitmap.getHeight() + bounds.height())/2-8;
  189.     Canvas canvas = new Canvas(scaleBitmap);
  190.     canvas.drawText(text,x,y,paint);
  191.     if(!bitmap.isRecycled())
  192.     {
  193.         bitmap.recycle();
  194.         bitmap = null;
  195.     }
  196.     return scaleBitmap;
  197. }
  198. }

  199. /**

    • 传入Bitmap和图片的Url名字,判断系统是否旋转过图片,如果旋转过则纠正
    • @param Bitmap
    • @param String
    • @return Bitmap
    • */
    • public static Bitmap changeRotation(Bitmap bmp,String path){
    • CompareActivity.IS_ROTATION = false;
    • int degree = 0;
    • ExifInterface exifInterface;
    • try {
    • exifInterface = new ExifInterface(path);
    • int tag = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,-1);
    • switch (tag) {
    • case ExifInterface.ORIENTATION_ROTATE_90:
    • degree = 90;
    • CompareActivity.IS_ROTATION = true;
    • break;
    • case ExifInterface.ORIENTATION_ROTATE_180:
    • degree = 180;
    • CompareActivity.IS_ROTATION = true;
    • break;
    • case ExifInterface.ORIENTATION_ROTATE_270:
    • degree = 270;
    • CompareActivity.IS_ROTATION = true;
    • break;
    • default:
    • break;
    • }
    • Matrix matrix = new Matrix();
    • matrix.postRotate(degree);
    • if (bmp != null){
    • bmp = Bitmap.createBitmap(bmp,bmp.getWidth(),bmp.getHeight(),true);
    • }
    • } catch (IOException e) {
    • e.printStackTrace();
    • }
    • return bmp;
    • }

猜你在找的程序笔记相关文章