在android中拍摄图像时压缩图像

时间:2012-11-02 05:34:35

标签: android

您好我正在开发一个CAMERA APPLICATION。拍摄图像后,图像将保存在SD卡中。我希望在保存sdcard时图像的大小应该是400kb到500kb,但现在它的占用量超过1mb。如何在捕获图像后压缩和保存SD卡。

我的代码是

 public void onClick(View v) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            imageName="MyCameraApp" + String.valueOf(System.currentTimeMillis()) + ".jpg";
            File file = new File(Environment.getExternalStorageDirectory()+"/pictures", imageName);
            fileUri = Uri.fromFile(file);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name

            startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

        }

2 个答案:

答案 0 :(得分:2)

我遇到了同样的问题,现在我修好了。我认为这对你有所帮助。如果你更改了SD卡的目录,我认为这段代码可以正常工作。

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_image_optimization);

    String dirname = Environment.getExternalStorageDirectory() + "/shahin/";

    File sddir = new File(dirname);
    if (!sddir.mkdirs()) {
        if (sddir.exists()) {
        } else {
            Toast.makeText(ImageOptimizationActivity.this, "Folder error", Toast.LENGTH_SHORT)
                    .show();
            return;
        }
    }

    try {
        Bitmap bitmap = null;
        File file = new File(Environment.getExternalStorageDirectory()
                + "/DCIM/101SHARP/rubon.jpg");
        try {
            bitmap = BitmapFactory.decodeStream(new FileInputStream(file));
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }

        FileOutputStream fos = new FileOutputStream(dirname + "output.jpg");
        bitmap.compress(CompressFormat.JPEG, 75, fos);

        fos.flush();
        fos.close();
    } catch (Exception e) {
        Log.e("MyLog", e.toString());
    }
}

}

答案 1 :(得分:0)

试试这个:

String root = Environment.getExternalStorageDirectory()
                    .toString();
            File myDir = new File(root + "/_images");
            myDir.mkdirs();
            Random generator = new Random();
            int n = 10000;
            n = generator.nextInt(n);
            String fname = "Image-" + n + ".jpg";
            file = new File(myDir, fname);
            Log.i(TAG, "" + file);
            if (file.exists())
                file.delete();
            try {
                FileOutputStream out = new FileOutputStream(file);
                bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

其中bm是位图图像