无法保存位图图像 [英] Not able to save the bitmap image

查看:113
本文介绍了无法保存位图图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我不存储我拍摄的图片。它显示在图像的观点,但我想保存图像,但图像不会在图像视图中显示。

 进口android.app.Activity;
进口android.app.AlertDialog;
进口android.content.DialogInterface;
进口android.content.Intent;
进口android.database.Cursor;
进口android.graphics.Bitmap;
进口android.graphics.BitmapFactory;
进口android.net.Uri;
进口android.os.Bundle;
进口android.os.Environment;
进口android.provider.MediaStore;
进口android.util.Log;
进口android.view.View;
进口android.widget.Button;
进口android.widget.ImageView;
进口的java.io.File;
进口java.io.FileOutputStream中;
进口java.text.SimpleDateFormat的;
进口java.util.Date;
公共类MainActivity延伸活动{
私有静态最终诠释CAMERA_REQUEST = 1;
私有静态诠释RESULT_LOAD_IMG = 1;
串imgDecodableString;
ImageView的IV;
BMP位图;@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);
    IV =(ImageView的)findViewById(R.id.imgView);
    按钮B =(按钮)findViewById(R.id.buttonLoadPicture);
    b.setOnClickListener(新View.OnClickListener(){
        @覆盖
        公共无效的onClick(视图v){
            selectImage();
        }
    });
}
公共无效selectImage(){    最终的CharSequence []选项= {拍摄照片,从图库中选择,取消};    AlertDialog.Builder建设者=新AlertDialog.Builder(MainActivity.this);
    builder.setTitle(添加照片!);
    builder.setItems(选项,新DialogInterface.OnClickListener(){
        @覆盖
        公共无效的onClick(DialogInterface对话,诠释项){
            如果(选项[项目] .equals(拍摄照片)){
                字符串路径= Environment.getExternalStorageDirectory()+/CameraImages/example.jpg
                档案文件=新的文件(路径);
                乌里outputFileUri = Uri.fromFile(文件);
                意向意图=新意图(android.provider.MediaStore.ACTION_IM​​AGE_CAPTURE);
                // intent.putExtra(MediaStore.EXTRA_OUTPUT,outputFileUri);                startActivityForResult(意向,1);
            }否则如果(选项[项目] .equals(从图库中选择)){
                意向意图=新意图(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(意向,2);
            }否则如果(选项[项目] .equals(取消)){
                dialog.dismiss();
            }
        }
    });
    builder.show();
}
@覆盖
保护无效的onActivityResult(INT申请code,INT结果code,意图数据){
super.onActivityResult(要求code,结果code,数据);
如果(结果code == RESULT_OK){
    如果(要求code == 1){
        如果(数据= NULL&放大器;!&安培;!data.getExtras()= NULL){
            。BMP =(位图)data.getExtras()获得(数据);
            Log.w(从图片库图片的路径...... ****************** .........,BMP +) ;
            iv.setImageBitmap(BMP);
        }
}其他{
        如果(要求code == 2){            乌里selectedImage = data.getData();
            的String []文件路径= {} MediaStore.Images.Media.DATA;
            光标C = getContentResolver()查询(selectedImage,文件路径,NULL,NULL,NULL);
            c.moveToFirst();
            INT参数:columnIndex = c.getColumnIndex(文件路径[0]);
            字符串picturePath = c.getString(参数:columnIndex);
            c.close();
            BMP =(BitmapFactory.de codeFILE(picturePath));
            Log.w(从图片库图片的路径...... ****************** .........,picturePath +) ;
            iv.setImageBitmap(BMP);
        }
    }
}}}


  

当一个加法intent.putExtra(MediaStore.EXTRA_OUTPUT,outputFileUri
  );图像被保存但在图像视图不显示



解决方案

下面是code我已经用于捕获和保存相机图像,然后显示给ImageView的。您可以根据您的需要使用。

您必须保存相机图像的具体位置,然后从该位置获取然后将其转换为字节数组。

下面是打开摄像机捕捉图像活度的方法。

 私有静态最终诠释CAMERA_PHOTO = 111;私人乌里imageToUploadUri;
私人无效captureCameraImage(){        意图chooserIntent =新意图(MediaStore.ACTION_IM​​AGE_CAPTURE);        文件f =新的文件(Environment.getExternalStorageDirectory()
POST_IMAGE.jpg);        chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(F));        imageToUploadUri = Uri.fromFile(F);        startActivityForResult(chooserIntent,CAMERA_PHOTO);    }

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

  @覆盖
        保护无效的onActivityResult(INT申请code,INT结果code,意图数据){
            super.onActivityResult(要求code,结果code,数据);            如果(要求code == CAMERA_PHOTO&放大器;&安培;结果code == Activity.RESULT_OK){
                如果(imageToUploadUri!= NULL){
                    乌里selectedImage = imageToUploadUri;
                    。getContentResolver()有NotifyChange(selectedImage,NULL);
                    位图reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
                    如果(reducedSizeBitmap!= NULL){
                        ImgPhoto.setImageBitmap(reducedSizeBitmap);
                        按钮uploadImageButton =(按钮)findViewById(R.id.uploadUserImageButton);
                          uploadImageButton.setVisibility(View.VISIBLE);
                    }其他{
                        Toast.makeText(这一点,错误同时捕捉图像,Toast.LENGTH_LONG).show();
                    }
                }其他{
                    Toast.makeText(这一点,错误同时捕捉图像,Toast.LENGTH_LONG).show();
                }
            }
        }

下面是getBitmap中使用的onActivityResult()()方法。我已经做了所有的性能提升,同时获得相机捕获图像的位图,可以是可能的。

 私人位图getBitmap(字符串路径){        URI URI = Uri.fromFile(新文件(路径));
        在的InputStream = NULL;
        尝试{
            最终诠释IMAGE_MAX_SIZE = 120; // 1.2MP
            在= getContentResolver()openInputStream(URI)。            //德code图像尺寸
            BitmapFactory.Options O =新BitmapFactory.Options();
            o.inJustDe codeBounds = TRUE;
            BitmapFactory.de codeStream(中,空,O);
            附寄();
            int标= 1;
            而((o.outWidth * o.outHeight)*(1 / Math.pow(规模,2))>
                    IMAGE_MAX_SIZE){
                规模++;
            }
            Log.d(,规模=+规模+,原稿宽度:+ o.outWidth +,原稿高度:+ o.outHeight);            位图B = NULL;
            在= getContentResolver()openInputStream(URI)。
            如果(规模大于1){
                规模 - ;
                //规模最大可能inSampleSize仍然产生的图像
                //比大目标
                O =新BitmapFactory.Options();
                o.inSampleSize =规模;
                B = BitmapFactory.de codeStream(中,空,O);                //调整到所需的尺寸
                INT高度= b.getHeight();
                INT宽度= b.getWidth();
                Log.d(,1号规模经营dimenions - 宽:+宽+,高度:+高);                双Y =的Math.sqrt(IMAGE_MAX_SIZE
                        /(((双)宽)/身高));
                双X =(Y /高)*宽;                位图scaledBitmap = Bitmap.createScaledBitmap(B,(INT)X,
                        (INT)Y,真正的);
                b.recycle();
                B = scaledBitmap;                System.gc()的;
            }其他{
                B = BitmapFactory.de codeStream(中);
            }
            附寄();            Log.d(,位图大小 - 宽:+ b.getWidth()+,高度:+
                    b.getHeight());
            返回b;
        }赶上(IOException异常五){
            Log.e(,e.getMessage(),E);
            返回null;
        }
    }

另外你保证你添加的所有权限在manifest文件

希望这将帮助你。

Here I am not storing the picture that I captured. It is displaying in the image view, but I am trying to save the image, however the image is not displaying in the image view.

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);
        }
    }
}}}

When an adding intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri ); image is saving but not displaying in image view

解决方案

Here is code I have used for Capturing and Saving Camera Image then display it to imageview. You can use according to your need.

You have to save Camera image to specific location then fetch from that location then convert it to byte-array.

Here is method for opening capturing camera image activity.

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);

    }

then your onActivityResult() method should be like this.

@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();
                }
            } 
        }

Here is getBitmap() method used in onActivityResult(). I have done all performance improvement that can be possible while getting camera capture image bitmap.

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;
        }
    }

Also you ensure that you added all permission in your manifest file

Hope this will Helps you

这篇关于无法保存位图图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆