Android - 压缩位图,然后将其保存到SDCARD的活动结果中

时间:2011-12-28 17:44:49

标签: android memory bitmap compression android-camera

我一直在沉溺于此,并不确定该怎么做。我要做的是:拍照,压缩到png(保持原始尺寸),然后将其保存到sdCard。我需要这样做的原因是因为我必须再次重新压缩它,然后Base64编码它,以便我可以将它发送到服务器。问题是1.文件太大2.我的内存不足3.不确定我是否正确执行此操作。

感谢您的帮助

这是我的代码:

@Override
public void onClick(View button) {
    switch (button.getId()) {
        case R.id.cameraButton:
            Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
                Uri.fromFile(new File("/sdcard/test.png")));
            startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
            break;
        case R.id.galleryButton:
            sendToDatabase();
            break;
    }
}

// Camera on activity for result - save it as a bmp and place in imageview
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAMERA_PIC_REQUEST) {
        // do something
    }

    if (resultCode == Activity.RESULT_OK) {
        Log.d(TAG, "result ok");

        picture = BitmapFactory.decodeFile("/sdcard/test.png");

        // Create string to place it in sd card
        String extStorageDirectory = Environment
                .getExternalStorageDirectory().toString();
        //create output stream
        OutputStream outputStream = null;
        //create file
        File file = new File(extStorageDirectory, "test.png");
        try {
            outputStream = new FileOutputStream(file);
            picture.compress(Bitmap.CompressFormat.PNG, 80, outputStream);
            //picture.recycle();
            outputStream.flush();
            outputStream.close();
        } catch (IOException e){
            Log.d(TAG, "ERROR");
        }
        imageView.setImageBitmap(picture);
    }
}

public void sendToDatabase() {
    InputStream inputStream = null;

    //get the picture from location
    picture = BitmapFactory.decodeFile("/sdcard/test.png");

    // CONVERT:
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    Boolean didItWork = picture.compress(Bitmap.CompressFormat.PNG, 50, outStream);
    picture.recycle();
    if (didItWork = true) {
        Log.d(TAG, "compression worked");
    }
    Log.d(TAG, "AFTER. Height: " + picture.getHeight() + " Width: "
        + picture.getWidth());
    final byte[] ba = outStream.toByteArray();
    try {
        outStream.close();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:13)

当你做picture.compress(Bitmap.CompressFormat.PNG,50,outStream);压缩不能作为无损的PNG工作,将忽略质量设置。因此参数50在这种情况下不起作用。所以我建议你把CompressFormat.PNG改成CompressFormat.JPEG。