调整位图照片的大小不会起作用

时间:2017-02-07 20:24:16

标签: android image bitmap resize size

我有这个小问题。我想用相机拍照。我拿它后我想保存在640 x 640像素。因此,我将5 MB的图像尺寸缩小到大约300 - 500 KB或更小,但是当我用相机拍摄图像时,它会保存到我的外部存储器,但从未将其转换为640 x 640.我得到原始图像尺寸这大约是4k分辨率。

目标是在位图内部保存640 x 640的图像,但不是原始尺寸。

这是代码

public class MainActivity extends AppCompatActivity {

    private static final String LOG_TAG = MainActivity.class.getSimpleName();

    private static final int CAMERA_REQUEST_CODE = 1;

    Button mBtnCamera;

    private Uri imageUri = null;

    int aleatorio;
    String foto;

    ImageView mImageView;

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

        mImageView = (ImageView) findViewById(R.id.imageView);

        aleatorio = Double.valueOf(Math.random() * 100).intValue();

        foto = Environment.getExternalStorageDirectory() + "/imagen" + aleatorio + ".jpg";

        mBtnCamera = (Button) findViewById(R.id.btnCamera);

        mBtnCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cameraIntent();
            }
        });

    }

    private void cameraIntent() {

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        imageUri = Uri.fromFile(new File(foto));

        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

        startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
    }

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

        if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {

            Bitmap image = BitmapFactory.decodeFile(foto);

            Bitmap resizedBitmap = Bitmap.createScaledBitmap(
                    image, 640, 640, false);

            File f = new File(foto);

            long size = f.length();

            Toast.makeText(this, size / (1024 * 1024) + " MB, " + f.getAbsolutePath(), Toast.LENGTH_LONG).show();

            mImageView.setImageBitmap(resizedBitmap);

        }
    }

    public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {
        int width = bm.getWidth();
        int height = bm.getHeight();
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // CREATE A MATRIX FOR THE MANIPULATION
        Matrix matrix = new Matrix();
        // RESIZE THE BIT MAP
        matrix.postScale(scaleWidth, scaleHeight);

        // "RECREATE" THE NEW BITMAP
        Bitmap resizedBitmap = Bitmap.createBitmap(
                bm, 0, 0, width, height, matrix, false);
        bm.recycle();
        return resizedBitmap;
    }

感谢

1 个答案:

答案 0 :(得分:0)

仅在这种情况下,resizedBitmap对象才存在于内存中。您应该将该对象写入存储。

看看这个解决方案:

MainActivity.java:

package szilard.sebok.myapplication;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private static final String LOG_TAG = MainActivity.class.getSimpleName();

    private static final int CAMERA_REQUEST_CODE = 1;

    Button mBtnCamera;

    private Uri imageUri = null;

    int aleatorio;
    String foto;

    ImageView mImageView;

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

        mImageView = (ImageView) findViewById(R.id.imageView);

        aleatorio = Double.valueOf(Math.random() * 100).intValue();

        foto = Environment.getExternalStorageDirectory() + "/imagen" + aleatorio + ".jpg";

        mBtnCamera = (Button) findViewById(R.id.btnCamera);

        mBtnCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cameraIntent();
            }
        });

    }

    private void cameraIntent() {

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        imageUri = Uri.fromFile(new File(foto));

        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

        startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
    }

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

        if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {

            Bitmap image = BitmapFactory.decodeFile(foto);

            Bitmap resizedBitmap = Bitmap.createScaledBitmap(image, 640, 640, false);
            //Lets create a new file for resizedBitmap
            // getExternalMediaDirs()[0].getPath() -> your first external media dir
            // and adding the file name for that: ...mediadir + /filename.png
            File resizedPng = new File(getExternalMediaDirs()[0].getPath() + "/resizedPng.png");
            try {
                //For testing I delete that if its exist
                if (resizedPng.exists()) {
                    resizedPng.delete();
                }
                if (resizedPng.createNewFile()) {
                    //Try to write the resizedBitmap object to the path
                    boolean successfullWrite = writeResizedBitmapToFile(resizedBitmap, resizedPng.getPath());
                    if (successfullWrite) {
                        boolean deleted  = tryToDeleOriginal(foto);
                        Toast.makeText(this, "WIN! Find your picture at: " + resizedPng.getPath() + "and is the original deleted? :" +String.valueOf(deleted), Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(this, "Fail :(", Toast.LENGTH_LONG).show();
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public boolean tryToDeleOriginal(String pathToOriginal){
        File f = new File (pathToOriginal);
        if (!f.isDirectory()){
            if (f.exists()){
              return f.delete();
            }
        }
        return false;
    }
    //This one is from the post that I linked before
    public boolean writeResizedBitmapToFile(Bitmap bmp, String filePath) {
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filePath);
            bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                    return true;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {
        int width = bm.getWidth();
        int height = bm.getHeight();
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // CREATE A MATRIX FOR THE MANIPULATION
        Matrix matrix = new Matrix();
        // RESIZE THE BIT MAP
        matrix.postScale(scaleWidth, scaleHeight);

        // "RECREATE" THE NEW BITMAP
        Bitmap resizedBitmap = Bitmap.createBitmap(
                bm, 0, 0, width, height, matrix, false);
        bm.recycle();
        return resizedBitmap;
    }
}

不要忘记清单上的渗透,加上这些:

<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
相关问题