Android 对大图的处理

Scale big bitmap and set Keyguard Wallpaper

private void processBigBitmapAndSetKeyguardWallpaper(Uri _uri) {

            InputStream inStream = null; //receive from uri
            InputStream reOpenStream = null; //Raise efficiency and avoid OOM
            InputStream outStream = null; //send to keyguard
            Uri uri = _uri;

            try {
                inStream = mContext.getContentResolver().openInputStream(uri);

                //API > 13
                WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
                Display display = wm.getDefaultDisplay();
                Point point = new Point();
                display.getRealSize(point);

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

                // For test the bitmap, just get the bitmap size, will not allocate memory for the big Bitmap
                opts.inJustDecodeBounds = true;
                BitmapFactory.decodeStream(inStream, null, opts);
                
                // Then scale the big bitmap
                int scale1 = Math.max(opts.outHeight, opts.outWidth)
                                    / Math.max(point.x, point.y);
                int scale2 = Math.min(opts.outHeight, opts.outWidth)
                                    / Math.min(point.x, point.y);

                opts.inSampleSize = Math.max(scale1, scale2);
                opts.inJustDecodeBounds = false;

                reOpenStream = mContext.getContentResolver().openInputStream(uri);

                Bitmap scaledBitmap = BitmapFactory.decodeStream(reOpenStream, null, opts);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                scaledBitmap.recycle();
                outStream = new ByteArrayInputStream(baos.toByteArray());
                WallpaperManager wallpaperManager = WallpaperManager
                        .getInstance(mContext);
                wallpaperManager.setKeyguardStream(outStream);

            } catch (FileNotFoundException e) {
                Log.d(TAG, uri.toString() + " not found" + e.toString());
            } catch (IOException e) {
                Log.d(TAG, "set keyguard error" + e.toString());
            } finally {
                try {
                    if (null != inStream)
                        inStream.close();

                    if(null != outStream)
                        outStream.close();

                    if(null != reOpenStream)
                        reOpenStream.close();

                } catch (IOException e) {
                    Log.d(TAG, "set keyguard error" + e.toString());
                }
            }
            return true;
        }

ref: http://blog.hesheyou.me/post/crop-large-image-with-android