无法保存位图图像

时间:2016-02-09 05:56:37

标签: android image bitmap save

这里我没有存储我拍摄的图片。它正在图像视图中显示,但我正在尝试保存图像,但图像未在图像视图中显示。

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.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;


public class MainActivity extends Activity {
private static final int CAMERA_REQUEST = 1;
private static int RESULT_LOAD_IMG = 1;
String imgDecodableString;
ImageView iv;
Bitmap bmp;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    iv = (ImageView) findViewById(R.id.imgView);
    Button b = (Button) findViewById(R.id.buttonLoadPicture);
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectImage();
        }
    });
}
public void selectImage() {

    final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setTitle("Add Photo!");
    builder.setItems(options, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (options[item].equals("Take Photo")) {
                String path = Environment.getExternalStorageDirectory() + "/CameraImages/example.jpg";
                File file = new File(path);
                Uri outputFileUri = Uri.fromFile(file);
                Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                //  intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri );

                startActivityForResult(intent, 1);
            } else if (options[item].equals("Choose from Gallery")) {
                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 2);
            } else if (options[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
    if (requestCode == 1) {
        if (data != null && data.getExtras() != null) {
            bmp = (Bitmap) data.getExtras().get("data");
            Log.w("path of image from gallery......******************.........", bmp + "");
            iv.setImageBitmap(bmp);
        }
}else {
        if (requestCode == 2) {

            Uri selectedImage = data.getData();
            String[] filePath = {MediaStore.Images.Media.DATA};
            Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePath[0]);
            String picturePath = c.getString(columnIndex);
            c.close();
            bmp = (BitmapFactory.decodeFile(picturePath));
            Log.w("path of image from gallery......******************.........", picturePath + "");
            iv.setImageBitmap(bmp);
        }
    }
}}}
  

添加intent.putExtra时(MediaStore.EXTRA_OUTPUT,outputFileUri   );图像正在保存但未在图像视图中显示

3 个答案:

答案 0 :(得分:1)

这是我用于捕获和保存摄像机图像然后将其显示到imageview的代码。您可以根据自己的需要使用。

您必须将摄像机图像保存到特定位置,然后从该位置获取,然后将其转换为字节数组。

这是打开拍摄相机图像活动的方法。

private static final int CAMERA_PHOTO = 111;

private Uri imageToUploadUri;


private void captureCameraImage() {

        Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        File f = new File(Environment.getExternalStorageDirectory(), 
"POST_IMAGE.jpg");

        chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));

        imageToUploadUri = Uri.fromFile(f);

        startActivityForResult(chooserIntent, CAMERA_PHOTO);

    }

那么你的onActivityResult()方法应该是这样的。

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

            if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
                if(imageToUploadUri != null){
                    Uri selectedImage = imageToUploadUri;
                    getContentResolver().notifyChange(selectedImage, null);
                    Bitmap reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
                    if(reducedSizeBitmap != null){
                        ImgPhoto.setImageBitmap(reducedSizeBitmap);
                        Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
                          uploadImageButton.setVisibility(View.VISIBLE);                
                    }else{
                        Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
                    }
                }else{
                    Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
                }
            } 
        }

这是onActivityResult()中使用的getBitmap()方法。在获取相机捕获图像位图时,我已经完成了所有性能改进。

private Bitmap getBitmap(String path) {

        Uri uri = Uri.fromFile(new File(path));
        InputStream in = null;
        try {
            final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
            in = getContentResolver().openInputStream(uri);

            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(in, null, o);
            in.close();


            int scale = 1;
            while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
                    IMAGE_MAX_SIZE) {
                scale++;
            }
            Log.d("", "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight);

            Bitmap b = null;
            in = getContentResolver().openInputStream(uri);
            if (scale > 1) {
                scale--;
                // scale to max possible inSampleSize that still yields an image
                // larger than target
                o = new BitmapFactory.Options();
                o.inSampleSize = scale;
                b = BitmapFactory.decodeStream(in, null, o);

                // resize to desired dimensions
                int height = b.getHeight();
                int width = b.getWidth();
                Log.d("", "1th scale operation dimenions - width: " + width + ", height: " + height);

                double y = Math.sqrt(IMAGE_MAX_SIZE
                        / (((double) width) / height));
                double x = (y / height) * width;

                Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
                        (int) y, true);
                b.recycle();
                b = scaledBitmap;

                System.gc();
            } else {
                b = BitmapFactory.decodeStream(in);
            }
            in.close();

            Log.d("", "bitmap size - width: " + b.getWidth() + ", height: " +
                    b.getHeight());
            return b;
        } catch (IOException e) {
            Log.e("", e.getMessage(), e);
            return null;
        }
    }

此外,您确保在清单文件中添加了所有权限

希望这会帮助你

答案 1 :(得分:0)

试试这个:

FileOutputStream out = null;
        String filename = getFilename();
        try {
            out = new FileOutputStream(filename);
            scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);

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




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

    }

答案 2 :(得分:0)

更改onActivityResult代码并将outputFileUri声明为global ...

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == 1) {

            BitmapFactory.Options options=new BitmapFactory.Options();
            options.inSampleSize=8;
            final Bitmap bitmap=BitmapFactory.decodeFile(outputFileUri.getPath(),options);
            Bitmap photo = bitmap;

                //Log.w("path of image from gallery......******************.........", bmp + "");
                iv.setImageBitmap(photo);

        }else {
            if (requestCode == 2) {

                Uri selectedImage = data.getData();
                String[] filePath = {MediaStore.Images.Media.DATA};
                Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
                c.moveToFirst();
                int columnIndex = c.getColumnIndex(filePath[0]);
                String picturePath = c.getString(columnIndex);
                c.close();
                bmp = (BitmapFactory.decodeFile(picturePath));
              //  Log.w("path of image from gallery......******************.........", picturePath + "");
                iv.setImageBitmap(bmp);
            }
        }
    }}