Android:自定义照片尺寸

标签 android android-camera image-resizing android-photos

我有一个应用程序,其中手机拍摄照片然后将其上传到服务器。我想先检查照片的大小,然后根据实际照片大小将照片大小缩小到某个特定大小。实际上在服务器上它不允许大于某个特定大小(比如 200 kb)的照片。

或者我可以限制相机只拍摄特定尺寸的照片,即使有人改变了相机的设置。

这里有很多问题要检索照片的宽度和高度。但我想以字节为单位自定义大小。

我使用 cameraIntent 打开相机

Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);

最佳答案

这是 AFAIK 唯一可能的解决方案,以减小尺寸..

public void onActivityResult(int requestcode, int resultcode, Intent data) {
        if (resultcode == RESULT_OK) {
            if (requestcode == SELECT_PICTURE) {
                Uri uri = data.getData();
                String imagePath = getPath(uri);
                int SCALE = 2;
                try{

                BitmapFactory.Options o2 = new BitmapFactory.Options();
                o2.inSampleSize = SCALE;
                Bitmap bitmap= BitmapFactory.decodeFile(imagePath, o2);
                OutputStream os = new FileOutputStream(imagePath);
                bitmap.compress(Bitmap.CompressFormat.PNG, 85, os);
                os.flush();
                os.close();
                File file = new File(imagePath);
                Log.i("Bitmap", "Height Width "+bitmap.getHeight()+" "+bitmap.getWidth());
                Log.i("File","Size in bytes "+file.length());
                while(file.length()>100*1024)
                {
                    SCALE +=2;
                    o2.inSampleSize = SCALE;
                    bitmap= BitmapFactory.decodeFile(imagePath, o2);
                    os = new FileOutputStream(imagePath);
                    bitmap.compress(Bitmap.CompressFormat.PNG, 85, os);
                    os.flush();
                    os.close();
                    file = new File(imagePath);
                    Log.i("Bitmap", "Height Width "+bitmap.getHeight()+" "+bitmap.getWidth());
                    Log.i("File","Size in bytes "+file.length());
                }
                bitmap = BitmapFactory.decodeFile(imagePath, o2);

                }
                catch (Exception e) {
                    e.printStackTrace();
                }
                txtimagepath.setText(imagePath);

            }
        }
    }



protected String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int columnIndex = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(columnIndex);

    }

关于Android:自定义照片尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13116634/

相关文章:

Android 相机支持的图片尺寸

C++、DirectX 9、Windows API - 调整大小会改变我的坐标吗?

java - 自动调整网格布局中 jbutton 图标的大小

html - 图像在 Firefox 中改变大小并失去质量

android - 无法让 adt 正常工作

java - Android Camera API - 强制关闭不释放相机资源

java - Android:相机表面 View 模糊

android - 将应用程序置于前台与在最近的 Activity 中按应用程序相同吗?

android - Android 上隐藏应用程序的 Intent

Android - 创建自己的文件夹以保存相机拍摄的图像