Bitmap 实现对图片压缩的2种方法小结

       好久没有写博客了,由于最近在忙于即时通信的项目,因此时间有点紧。对于项目上遇到的问题,我会陆续贴出来,以供参考。服务器

好了很少说了,在聊天的时候也常常会遇到对于图片的处理,由于用户除了发消息外还能够发图片,对于发送图片,方法一:咱们能够将图片先压缩而后转换成流,再将流发送给另外一端用户,用户接受到的是压缩后的流,再对流转换成图片,这时用户看到的是压缩后的图片,若是想看高清图片,必须在发送端出将图片上传到服务器,接收端用户点击缩略图后开始下载高清图,最后呈现的就是所谓的大图,固然有人说能够对发送端发过来的压缩图片进行解压缩,我不知道这种方法行不行,尚未试。还有另外一种方法是直接发送一个路径,将图片上传到服务器中,接收端收到的是一个路径,而后根据路径去服务器下载图片,这种也不失为一种好方法。spa

     我使用的是上面所说的第一种方法,这种方法确实有点繁琐,但同样能够实现发送图片。code

//对图片压缩orm

方法一:对图片的宽高进行压缩blog

 1 // 根据路径得到图片并压缩,返回bitmap用于显示
 2     public static Bitmap getSmallBitmap(String filePath) {//图片所在SD卡的路径
 3         final BitmapFactory.Options options = new BitmapFactory.Options();
 4         options.inJustDecodeBounds = true;
 5         BitmapFactory.decodeFile(filePath, options);
 6         options.inSampleSize = calculateInSampleSize(options, 480, 800);//自定义一个宽和高
 7         options.inJustDecodeBounds = false;
 8         return BitmapFactory.decodeFile(filePath, options);
 9      }
10     
11     //计算图片的缩放值
12     public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight) {
13         final int height = options.outHeight;//获取图片的高
14         final int width = options.outWidth;//获取图片的框
15         int inSampleSize = 4;
16         if (height > reqHeight || width > reqWidth) {
17              final int heightRatio = Math.round((float) height/ (float) reqHeight);
18              final int widthRatio = Math.round((float) width / (float) reqWidth);
19              inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
20         }
21         return inSampleSize;//求出缩放值
22     }

 

其实还有一种写法是不须要这么麻烦的,直接写他的压缩率就行图片

 1 //根据路径获取用户选择的图片
 2     public  static Bitmap getImage(String imgPath){
 3         BitmapFactory.Options options=new BitmapFactory.Options();
 4         options.inSampleSize=2;//直接设置它的压缩率,表示1/2
 5         Bitmap b=null;
 6         try {
 7             b=BitmapFactory.decodeFile(imgPath, options);
 8         } catch (Exception e) {
 9             e.printStackTrace();
10         }
11         return b;
12     } 

 

方法二:对图片的质量压缩,主要方法就是compress()get

//将图片转成成Base64流博客

1 //将Bitmap转换成Base64
2     public static String getImgStr(Bitmap bit){
3        ByteArrayOutputStream bos=new ByteArrayOutputStream();
4        bit.compress(CompressFormat.JPEG, 40, bos);//参数100表示不压缩
5        byte[] bytes=bos.toByteArray();
6        return Base64.encodeToString(bytes, Base64.DEFAULT);
7     }    

//将Base64流转换成图片it

1 //将Base64转换成bitmap
2     public static Bitmap getimg(String str){
3         byte[] bytes;
4         bytes=Base64.decode(str, 0);
5         return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
6     }    


好吧,暂时写到这里,之后再修改.....io

相关文章
相关标签/搜索