压缩图片

时间:2015-12-15 17:16:10

标签: java android-studio bitmap

在我的应用程序中,有一个“上传图片”的按钮:从相机拍摄照片或从图库中选择。

在这两个选项中,有3个问题:

1)再次点击上传另一张图片时 - 应用程序会崩溃

2)在第一次“上传”时,图片在侧面旋转(逆时针旋转90度)

3)图片的大小是原始大小,我希望它被压缩到125x125的分辨率。

请帮助(即使你有一个问题的解决方案)

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import entities.Order;


public class SellABookFragment extends Fragment implements View.OnClickListener {

    private ImageView ivBookPicture;
    private EditText etBookName, etBookAuthor, etBookGenre, etBookPublishing, etQuantity, etBookPrice, etBookDetails;
    private Button bUploadPicture, bAddBook;

    public SellABookFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_sell_a_book, container, false);
        ivBookPicture = (ImageView) view.findViewById(R.id.ivBook_Picture);
        etBookName = (EditText) view.findViewById(R.id.etBook_Name);
        etBookAuthor = (EditText) view.findViewById(R.id.etAuthor_Name);
        etBookGenre = (EditText) view.findViewById(R.id.etGenre);
        etBookPublishing = (EditText) view.findViewById(R.id.etPublishing_Year);
        etQuantity = (EditText) view.findViewById(R.id.etBook_Quantity);
        etBookPrice = (EditText) view.findViewById(R.id.etBook_Price);
        etBookDetails = (EditText) view.findViewById(R.id.etBook_Details);
        bUploadPicture = (Button) view.findViewById(R.id.bUpload_Picture);
        bAddBook = (Button) view.findViewById(R.id.bAdd_Book);

        bUploadPicture.setOnClickListener(this);
        bAddBook.setOnClickListener(this);
        return view;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bUpload_Picture:
                selectPicture();
                break;
            case R.id.bAdd_Book:
                addBook();
                break;
        }
    }

    private void addBook() {
        try {
            HomeActivity.backEnd.addOrder(new Order(HomeActivity.LoggedUser.getID(),
                    etBookGenre.getText().toString(),
                    etBookName.getText().toString(),
                    Integer.parseInt(etBookPublishing.getText().toString()),
                    etBookAuthor.getText().toString(),
                    Double.parseDouble(etBookPrice.getText().toString()),
                    (Integer) ivBookPicture.getTag()));
        } catch (Exception e) {
            Toast.makeText(getActivity().getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    private void selectPicture() {
        final CharSequence[] options = {
                getResources().getString(R.string.take_photo),
                getResources().getString(R.string.gallery_choose),
                getResources().getString(R.string.cancel)};
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(getResources().getString(R.string.upload_picture));
        builder.setItems(options, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (options[item].equals(getResources().getString(R.string.take_photo))) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File f = new File(android.os.Environment.getExternalStorageDirectory(), "tmp.jpg");
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                    startActivityForResult(intent, 1);
                } else if (options[item].equals(getResources().getString(R.string.gallery_choose))) {
                    Intent intent = new Intent(Intent.ACTION_PICK,
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, 2);
                } else
                    dialog.dismiss();
            }
        });
        builder.show();
    }

    Bitmap bitmap;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        OutputStream outFile;
        String path = android.os.Environment.getExternalStorageDirectory()
                + File.separator
                + "MyApp";
        File file;
        if (resultCode == Activity.RESULT_OK) {
            if (bitmap != null) {
                ivBookPicture.setImageBitmap(null);
                bitmap.recycle();
                bitmap = null;
            }
            try {
                if (requestCode == 1) {
                    File f = new File(Environment.getExternalStorageDirectory().toString());
                    for (File tmp : f.listFiles()) {
                        if (tmp.getName().equals("tmp.jpg")) {
                            f = tmp;
                            break;
                        }
                    }
                    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
                    bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(), bitmapOptions);
                    ivBookPicture.setImageBitmap(bitmap);
                    if (f.delete()) {
                        file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
                        try {
                            outFile = new FileOutputStream(file);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                } else if (requestCode == 2) {
                    Uri selectedImage = data.getData();
                    String[] filePath = {MediaStore.Images.Media.DATA};
                    Cursor c = getActivity().getContentResolver().query(selectedImage, filePath, null, null, null);
                    c.moveToFirst();
                    int columnIndex = c.getColumnIndex(filePath[0]);
                    String picturePath = c.getString(columnIndex);
                    c.close();
                    bitmap = (BitmapFactory.decodeFile(picturePath));
                    Log.w("image path", picturePath);
                    ivBookPicture.setImageBitmap(bitmap);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

包含上传图片的ImageView:

            <ImageView
                android:id="@+id/ivBook_Picture"
                android:layout_width="@dimen/sell_a_book_picture_size"
                android:layout_height="@dimen/sell_a_book_picture_size"
                android:src="@mipmap/ic_launcher" />

谢谢!

1 个答案:

答案 0 :(得分:1)

 public Bitmap compressBySize(String pathName, int targetWidth,  
            int targetHeight) {  
        BitmapFactory.Options opts = new BitmapFactory.Options();  
        opts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(pathName, opts);    
        int imgWidth = opts.outWidth;  
        int imgHeight = opts.outHeight;  
        int widthRatio = (int) Math.ceil(imgWidth / (float) targetWidth);  
        int heightRatio = (int) Math.ceil(imgHeight / (float) targetHeight);  
        if (widthRatio > 1 || heightRatio > 1) {  
            if (widthRatio > heightRatio) {  
                opts.inSampleSize = widthRatio;  
            } else {  
                opts.inSampleSize = heightRatio;  
            }  
        }  

        opts.inJustDecodeBounds = false;  
        bitmap = BitmapFactory.decodeFile(pathName, opts);  
        return bitmap;  
    }  

使用此方法进行压缩,只需自己设置 targetWidth&amp; targetHeight

此外,您可以使用bitmap.compress(Bitmap.CompressFormat.JPEG, compressRate, byteOutputStream);按质量压缩位图。

对于崩溃,这是因为图片位图占用了太多内存。您应该压缩图片并记住在首次上传后释放内存。您可以考虑使用 WeakReference