compress Bitmap Image by scaling the image - Android Graphics

Android examples for Graphics:Bitmap Compress

Description

compress Bitmap Image by scaling the image

Demo Code

/**/*  w  ww  . ja  v a  2  s . co  m*/
 * Copyright 2014 Zhenguo Jin
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//package com.java2s;

import java.io.ByteArrayOutputStream;

import android.graphics.Bitmap;

import android.graphics.Matrix;

public class Main {

    public static void compress(Bitmap bitmap, double maxSize) {
        // bitmapbitmap
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 
        bitmap.compress(Bitmap.CompressFormat.PNG, 70, baos);
        byte[] b = baos.toByteArray();
        // KB
        double mid = b.length / 1024;
        // bitmap 
        double i = mid / maxSize;
        // bitmap  
        if (i > 1) {
            bitmap = scale(bitmap, bitmap.getWidth() / Math.sqrt(i),
                    bitmap.getHeight() / Math.sqrt(i));
        }
    }

    public static Bitmap scale(Bitmap src, double newWidth, double newHeight) {
        // src
        float width = src.getWidth();
        float height = src.getHeight();
        // matrix
        Matrix matrix = new Matrix();
        // 
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 
        matrix.postScale(scaleWidth, scaleHeight);
        // 
        return Bitmap.createBitmap(src, 0, 0, (int) width, (int) height,
                matrix, true);
    }

    public static Bitmap scale(Bitmap src, Matrix scaleMatrix) {
        return Bitmap.createBitmap(src, 0, 0, src.getWidth(),
                src.getHeight(), scaleMatrix, true);
    }

    public static Bitmap scale(Bitmap src, float scaleX, float scaleY) {
        Matrix matrix = new Matrix();
        matrix.postScale(scaleX, scaleY);
        return Bitmap.createBitmap(src, 0, 0, src.getWidth(),
                src.getHeight(), matrix, true);
    }

    public static Bitmap scale(Bitmap src, float scale) {
        return scale(src, scale, scale);
    }
}

Related Tutorials