小米3手機上加載相冊圖片失敗的問題

機型小米3W,ROM4.4.4廢話很少說,在加載相冊圖片時報了這樣一個錯誤html

09-16 12:26:53.270: W/OpenGLRenderer(21987): Bitmap too large to be uploaded into a texture (4208x2368, max=4096x4096)

裁剪唄,網上找了個算法,挺好使,貼到這裏,記錄下android

在作相冊應用的過程當中,須要獲得一個壓縮過的縮略圖但,同時我還但願獲得的bitmap可以是正方形的,以適應正方形的imageView,傳統設置inSampleSize壓縮比率的方式只是壓縮了整張圖片,若是一個圖片的長寬差距較大,則展現出來的時候會有拉伸的現象,所以正確的作法是在壓縮以後,對bitmap進行裁剪。算法

代碼以下:spa

給定圖片維持寬高比縮放後,截取正中間的正方形部分code

 1 /**
 2                                                                       
 3    * @param bitmap      原圖
 4    * @param edgeLength  但願獲得的正方形部分的邊長
 5    * @return  縮放截取正中部分後的位圖。
 6    */
 7   public static Bitmap centerSquareScaleBitmap(Bitmap bitmap, int edgeLength)
 8   {
 9    if(null == bitmap || edgeLength <= 0)
10    {
11     return  null;
12    }
13                                                                                  
14    Bitmap result = bitmap;
15    int widthOrg = bitmap.getWidth();
16    int heightOrg = bitmap.getHeight();
17                                                                                  
18    if(widthOrg > edgeLength && heightOrg > edgeLength)
19    {
20     //壓縮到一個最小長度是edgeLength的bitmap
21     int longerEdge = (int)(edgeLength * Math.max(widthOrg, heightOrg) / Math.min(widthOrg, heightOrg));
22     int scaledWidth = widthOrg > heightOrg ? longerEdge : edgeLength;
23     int scaledHeight = widthOrg > heightOrg ? edgeLength : longerEdge;
24     Bitmap scaledBitmap;
25                                                                                   
26           try{
27            scaledBitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, true);
28           }
29           catch(Exception e){
30            return null;
31           }
32                                                                                        
33        //從圖中截取正中間的正方形部分。
34        int xTopLeft = (scaledWidth - edgeLength) / 2;
35        int yTopLeft = (scaledHeight - edgeLength) / 2;
36                                                                                      
37        try{
38         result = Bitmap.createBitmap(scaledBitmap, xTopLeft, yTopLeft, edgeLength, edgeLength);
39         scaledBitmap.recycle();
40        }
41        catch(Exception e){
42         return null;
43        }       
44    }
45                                                                                       
46    return result;
47   }

須要注的是bitmap參數必定要是從原圖獲得的,若是是已經通過BitmapFactory inSampleSize壓縮過的,可能會不是到正方形。htm

原始頁面在這裏blog

http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2014/0917/1686.html
相關文章
相關標籤/搜索