压缩图像导致错误 Android

Compress Image cause Error in Android

从智能手机点击照片时,图片太大,上传需要几分钟时间,所以我想在不影响质量的情况下减小图片尺寸。所以我从这个网站 link 得到了代码。但是在我现有的代码中添加代码时,有一些编译器错误已修复。

以下错误在 compressImage(String imageUri) 函数

  1. scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);

    错误是:cannot resolve mrthod 'setScale(float,float,float)'

  2. canvas.setMatrix(scaleMatrix);

    错误是:setMatrix (android.graphics.Matrix) in Canvas cannot be applied to (android.opengl.Matrix)

  3. matrix.postRotate(90);

  4. matrix.postRotate(180);

  5. matrix.postRotate(270);

    错误是:cannot resolve method 'postRotate(int)'

代码:

public class Camera extends AppCompatActivity implements View.OnClickListener {

    public static final String UPLOAD_URL = "http://website.com/ImageUpload/upload.php";
    public static final String UPLOAD_KEY = "image";
    public static final String UPLOAD_NAME = "name";
    public static final String UPLOAD_EMAIL = "email";
    public static final String UPLOAD_PHONE= "phone";
    public static final String TAG = "MY MESSAGE";
    boolean b=false,z;
    private int PICK_IMAGE_REQUEST = 1;
    String mock;
    private Button buttonChoose;
    String uploadImage;
    private Button buttonUpload,buttonView;
    private ImageView imageView;
    private Bitmap bitmap,bitmaps;
    private Uri filePath;
    String path;
    String[] max;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.camera);

        buttonChoose = (Button) findViewById(R.id.buttonChoose);
        buttonUpload = (Button) findViewById(R.id.buttonUpload);

      buttonView = (Button) findViewById(R.id.buttonViewImage);

        buttonUpload.setEnabled(false);

        imageView = (ImageView) findViewById(R.id.imageView);
        buttonChoose.setOnClickListener(this);
        buttonUpload.setOnClickListener(this);
        buttonView.setOnClickListener(this);


       /* GetSet b= new GetSet();
        String maths=b.getCombine();
*/
    //    System.out.println("Matru "+maths);


        Bundle bundle = getIntent().getExtras();

        //Extract the data…
        String stuff = bundle.getString("combine_data");
        // String sss = bundle.getString("combine_data2");

        System.out.println("changa " + stuff);

        max=stuff.split("~");

        for(int i=0;i<max.length;i++)
            System.out.println("binku " + max[i]);



    }


    private void selectImage() {

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
        startActivityForResult(intent, 1);


    }


    private void showFileChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if(b) {
            if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

                filePath = data.getData();
                try {
                    bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                    imageView.setImageBitmap(bitmap);
                    buttonUpload.setEnabled(true);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

        else {

            if (resultCode == RESULT_OK) {
                if (requestCode == 1) {
                    File f = new File(Environment.getExternalStorageDirectory().toString());
                    for (File temp : f.listFiles()) {
                        if (temp.getName().equals("temp.jpg")) {
                            f = temp;
                            break;
                        }
                    }
                    try {

                        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();

                        bitmaps = BitmapFactory.decodeFile(f.getAbsolutePath(),
                                bitmapOptions);

                        imageView.setImageBitmap(bitmaps);
                        buttonUpload.setEnabled(true);
                          mock= getStringImage(bitmaps);

                        String path = android.os.Environment
                                .getExternalStorageDirectory()
                                + File.separator
                                + "Phoenix" + File.separator + "default";
                        f.delete();
                        OutputStream outFile = null;
                        File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
                        try {
                            outFile = new FileOutputStream(file);
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
                            outFile.flush();
                            outFile.close();
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }

    public String getStringImage(Bitmap bmp){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        return encodedImage;
    }

    private void uploadImage(){
        class UploadImage extends AsyncTask<Bitmap,Void,String>{

            ProgressDialog loading;
            RequestHandler rh = new RequestHandler();

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(Camera.this, "Uploading Image", "Please wait...",true,true);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
                imageView.setImageDrawable(null);
                buttonUpload.setEnabled(false);
            }

            @Override
            protected String doInBackground(Bitmap... params) {
                Bitmap bitmap = params[0];
                if(z)
                uploadImage = getStringImage(bitmap);
                else
                    uploadImage = mock;

                String compress_image=compressImage(uploadImage);

                HashMap<String,String> data = new HashMap<>();
                data.put(UPLOAD_KEY, compress_image);
                data.put(UPLOAD_NAME,max[0]);
                data.put(UPLOAD_EMAIL,max[2]);
                data.put(UPLOAD_PHONE,max[1]);

                String result = rh.sendPostRequest(UPLOAD_URL,data);

                return result;

            }
        }

        UploadImage ui = new UploadImage();
        ui.execute(bitmap);
    }



    public String compressImage(String imageUri) {

        path = getRealPathFromURI(imageUri);
        Bitmap scaledBitmap = null;

        BitmapFactory.Options options = new BitmapFactory.Options();

//      by setting this field as true, the actual bitmap pixels are not loaded in the memory. Just the bounds are loaded. If
//      you try the use the bitmap here, you will get null.
        options.inJustDecodeBounds = true;
        Bitmap bmp = BitmapFactory.decodeFile(path, options);

        int actualHeight = options.outHeight;
        int actualWidth = options.outWidth;

//      max Height and width values of the compressed image is taken as 816x612

        float maxHeight = 816.0f;
        float maxWidth = 612.0f;
        float imgRatio = actualWidth / actualHeight;
        float maxRatio = maxWidth / maxHeight;

//      width and height values are set maintaining the aspect ratio of the image

        if (actualHeight > maxHeight || actualWidth > maxWidth) {
            if (imgRatio < maxRatio) {
                imgRatio = maxHeight / actualHeight;
                actualWidth = (int) (imgRatio * actualWidth);
                actualHeight = (int) maxHeight;
            } else if (imgRatio > maxRatio) {
                imgRatio = maxWidth / actualWidth;
                actualHeight = (int) (imgRatio * actualHeight);
                actualWidth = (int) maxWidth;
            } else {
                actualHeight = (int) maxHeight;
                actualWidth = (int) maxWidth;

            }
        }

//      setting inSampleSize value allows to load a scaled down version of the original image

        options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);

//      inJustDecodeBounds set to false to load the actual bitmap
        options.inJustDecodeBounds = false;

//      this options allow android to claim the bitmap memory if it runs low on memory
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inTempStorage = new byte[16 * 1024];

        try {
//          load the bitmap from its path
            bmp = BitmapFactory.decodeFile(path, options);
        } catch (OutOfMemoryError exception) {
            exception.printStackTrace();

        }
        try {
            scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight,Bitmap.Config.ARGB_8888);
        } catch (OutOfMemoryError exception) {
            exception.printStackTrace();
        }

        float ratioX = actualWidth / (float) options.outWidth;
        float ratioY = actualHeight / (float) options.outHeight;
        float middleX = actualWidth / 2.0f;
        float middleY = actualHeight / 2.0f;



        Matrix scaleMatrix = new Matrix();
        scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);

        Canvas canvas = new Canvas(scaledBitmap);
        canvas.setMatrix(scaleMatrix);
        canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));

//      check the rotation of the image and display it properly
        ExifInterface exif;
        try {
            exif = new ExifInterface(path);

            int orientation = exif.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            Log.d("EXIF", "Exif: " + orientation);
            Matrix matrix = new Matrix();
            if (orientation == 6) {
                matrix.postRotate(90);
                Log.d("EXIF", "Exif: " + orientation);
            } else if (orientation == 3) {
                matrix.postRotate(180);
                Log.d("EXIF", "Exif: " + orientation);
            } else if (orientation == 8) {
                matrix.postRotate(270);
                Log.d("EXIF", "Exif: " + orientation);
            }

            scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
        } catch (IOException e) {
            e.printStackTrace();
        }

        FileOutputStream out = null;
        String filename = getFilename();
        try {
            out = new FileOutputStream(filename);

//          write the compressed bitmap at the destination specified by filename.
            scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return filename;

    }

    private String getRealPathFromURI(String contentURI) {
        Uri contentUri = Uri.parse(contentURI);
        Cursor cursor = getContentResolver().query(contentUri, null, null, null, null);
        if (cursor == null) {
            return contentUri.getPath();
        } else {
            cursor.moveToFirst();
            int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            return cursor.getString(index);
        }
    }

    public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height/ (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;      }       final float totalPixels = width * height;       final float totalReqPixelsCap = reqWidth * reqHeight * 2;       while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
            inSampleSize++;
        }

        return inSampleSize;
    }

    public String getFilename() {
        File file = new File(Environment.getExternalStorageDirectory().getPath(), "MyFolder/Images");
        if (!file.exists()) {
            file.mkdirs();
        }
        String uriSting = (file.getAbsolutePath() + "/" + System.currentTimeMillis() + ".jpg");
        return uriSting;

    }

    @Override
    public void onClick(View v) {
        if (v == buttonChoose) {
            b=true;
            z=true;
            showFileChooser();

        }
        if(v == buttonUpload) {

                uploadImage();
        }

        if(v == buttonView){
            b=false;
            z=false;
            selectImage();

        }

    }
}

我想如果你减小位图大小那么你可能会解决这个问题-

public static Bitmap getBitmapFromByteArray(final byte data[], int maxSize) {
    final int MAX_SIZE = maxSize;
    if (data.length > 0) {
        try {
            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,
                    data.length, options);
            final int fullWidth = options.outWidth;
            final int fullHeight = options.outHeight;
            int w = 0;
            int h = 0;
            if (fullWidth > fullHeight) {
                w = MAX_SIZE;
                h = w * fullHeight / fullWidth;
            } else {
                h = MAX_SIZE;
                w = h * fullWidth / fullHeight;
            }
            options.inJustDecodeBounds = false;
            options.inSampleSize = fullWidth / w;
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,
                    options);
            return bitmap;
        } catch (final Exception e) {
        }
    }
    return null;
}

您将发送当前位图 ByteArray 数据,其大小是您希望从该位图中得到的。然后它将 return 位图调整大小。你可以试试这个。

可以通过两种方式实现,即降低 jpeg 质量或调整图像大小。

调整图像大小

Bitmap mBitmap = Bitmap.createScaledBitmap(bitmap, 480, 300, true);

降低 jpeg 质量

bitmap.compress(Bitmap.CompressFormat.JPEG, 60, outFile);