Bitmap 實現對圖片壓縮的2種方法小結


       很久沒有寫博客了,因為最近在忙於即時通訊的項目,所以時間有點緊。對於項目上遇到的問題,我會陸續貼出來,以供參考。

好了不多說了,在聊天的時候也經常會遇到對於圖片的處理,因為用戶除了發消息外還可以發圖片,對於發送圖片,方法一:我們可以將圖片先壓縮然后轉換成流,再將流發送給另一端用戶,用戶接受到的是壓縮后的流,再對流轉換成圖片,這時用戶看到的是壓縮后的圖片,如果想看高清圖片,必須在發送端出將圖片上傳到服務器,接收端用戶點擊縮略圖后開始下載高清圖,最后呈現的就是所謂的大圖,當然有人說可以對發送端發過來的壓縮圖片進行解壓縮,我不知道這種方法行不行,還沒有試。還有另一種方法是直接發送一個路徑,將圖片上傳到服務器中,接收端收到的是一個路徑,然后根據路徑去服務器下載圖片,這種也不失為一種好方法。

     我使用的是上面所說的第一種方法,這種方法確實有點繁瑣,但一樣可以實現發送圖片。

//對圖片壓縮

方法一:對圖片的寬高進行壓縮

 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()

//將圖片轉成成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流轉換成圖片

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     }    


好吧,暫時寫到這里,以后再修改.....

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM