0

您好,我正在开发相机应用程序。拍摄图像后,图像将保存在 sdcard 中。我希望在保存 sdcard 时图像的大小应该是 400kb 到 500kb,但现在它需要超过 1mb。如何在捕获图像后压缩并保存在 sdcard 中。

我的代码是

 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);

        }
4

2 回答 2

2

我遇到了同样的问题,现在我解决了。我想这对你会有帮助。如果您更改 sdcard 的目录,我认为此代码可以正常工作。

@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());
    }
}

}

于 2012-11-02T06:33:45.900 回答
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 是位图图像

于 2012-11-02T05:51:22.753 回答