压缩bitmat时出错

时间:2015-08-07 11:39:04

标签: android bitmap android-bitmap bitmapfactory

我正在尝试压缩位图,但是获取空指针异常...... logcat显示未捕获的异常

 Bitmap bitmap = BitmapFactory.decodeByteArray(imageAsBytes , 0, imageAsBytes .length);
                Bitmap bPNGcompress =codec(bitmap, Bitmap.CompressFormat.PNG, 0);


                Bitmap scaled = bPNGcompress.createScaledBitmap( bPNGcompress, 100, 100, true );

方法实现

  private static Bitmap codec(Bitmap map, Bitmap.CompressFormat format,
        int quality) {

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    map.compress(format, quality, os);
    try {
        os.flush();
        os.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    byte[] array = os.toByteArray();
    return BitmapFactory.decodeByteArray(array, 0, array.length);
}

1 个答案:

答案 0 :(得分:0)

请试试这个,

 private static Bitmap codec(Bitmap src, Bitmap.CompressFormat format,int quality) 
   {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    src.compress(format, quality, os);

    byte[] array = os.toByteArray();
    return BitmapFactory.decodeByteArray(array, 0, array.length);
}

private static class SampleView extends View {

    // CONSTRUCTOR
    public SampleView(Context context) {
        super(context);
        setFocusable(true);

    }
    @Override
    protected void onDraw(Canvas canvas) {
        Paint paint = new Paint();

        canvas.drawColor(Color.GRAY);

                    //  you need to insert some image flower_blue into res/drawable folder
        Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.flower_blue);
                    // Best of quality is 80 and more, 3 is very low quality of image 
        Bitmap bJPGcompress = codec(b, Bitmap.CompressFormat.JPEG, 3);
               // get dimension of bitmap getHeight()  getWidth()
       int h = b.getHeight();

       canvas.drawBitmap(b, 10,10, paint);
       canvas.drawBitmap(bJPGcompress, 10,10 + h + 10, paint);

    }

}