在onActivityResult中,当我尝试从相机获取uri并将其转换为bytearray时,bytearray为null

时间:2015-12-16 04:18:08

标签: android camera uri bytearray

我正在创建一个功能,当用户从相机中捕获图像时,它会显示图片。但当进程转到onActivityResult时,我会尝试将其转换为byte[],但它会出现空值。我不明白为什么。

这是我的代码:

     @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {

            Uri selectedImageUri = data.getData();

            //Camera
            if (selectedImageUri == null) {
                selectedImageUri = outputFileUri;
            }

            try {
                imageOutputStream = new FileOutputStream(sdImageMainDirectory);

            }
            catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            //Code to add attachment row to the attachment list view
            claimattachmenturi = selectedImageUri;


            claimattachmentfilename = getUniqueImageFilenameForShowing();
            claimattachmentpathname = getUniqueImageFilenameForFilename();


            try{claimattachmentbytearray = uriToByteArray(selectedImageUri); }
            catch(FileNotFoundException e){e.printStackTrace();}
            catch(IOException e){e.printStackTrace();}



             try{claimattachmentbitmap = UriToBitmap(claimattachmenturi);}
             catch (FileNotFoundException e){}

            newAttachment = new AttachmentListResult();
            newAttachment.setBitmap(claimattachmentbitmap);
            newAttachment.setDirectory(sdImageMainDirectory);
            newAttachment.setFilename(claimattachmentfilename);
            newAttachment.setPathname(claimattachmentpathname);
            newAttachment.setByteArray(claimattachmentbytearray);
            if(lastAdapter != null) {attachmentarray = lastAdapter.getAttachmentArray();}

            attachmentarray.add(newAttachment);

            listViewUpdate();
        }
    }
}

转换方法:

       private byte[] bitmapToByteArray(Bitmap bitmap)
{
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 0, stream);
    byte[] byteArray = stream.toByteArray();
    return byteArray;
}

private byte[] uriToByteArray(Uri uri) throws FileNotFoundException, IOException
{
    InputStream inputStream = getContentResolver().openInputStream(uri);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    int bufferSize = 1024, length = 0;
    byte[] buffer = new byte[bufferSize];
while((length = inputStream.read(buffer)) != -1){
    byteArrayOutputStream.write(buffer, 0, length);
}
    return byteArrayOutputStream.toByteArray();
}

我可以将File Scheme URI转换为Content Scheme URI吗? 我真的需要一些帮助。

1 个答案:

答案 0 :(得分:0)

 public void takePhoto()
 {
    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
    File folder = new File(Environment.getExternalStorageDirectory() + "/LoadImg");

    if(!folder.exists())
    {
        folder.mkdir();
    }
    final Calendar c = Calendar.getInstance();
    String new_Date= c.get(Calendar.DAY_OF_MONTH)+"-"+((c.get(Calendar.MONTH))+1)   +"-"+c.get(Calendar.YEAR) +" " + c.get(Calendar.HOUR) + "-" + c.get(Calendar.MINUTE)+ "-"+ c.get(Calendar.SECOND);
    path=String.format(Environment.getExternalStorageDirectory() +"/LoadImg/%s.png","LoadImg("+new_Date+")");
    File photo = new File(path);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
    startActivityForResult(intent, 2);
}

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

    if(requestCode==1)
    {
        if(data!=null) {
            Uri photoUri = data.getData();
            if (photoUri != null) {
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(photoUri, filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String filePath = cursor.getString(columnIndex);
                cursor.close();
                Log.v("Load Image", "Gallery File Path=====>>>" + filePath);
                photo_url = filePath;
                //Log.v("Load Image", "Image List Size=====>>>"+image_list.size());

                //updateImageTable();
                new GetImages().execute();
            }
        }
    }

    if(requestCode==2)
    {
        Log.v("Load Image", "Camera File Path=====>>>"+path);
        photo_url = path;
        //Log.v("Load Image", "Image List Size=====>>>"+image_list.size());
       // updateImageTable();
        new GetImages().execute();

    }
}

public void updateImageTable()
{


    displayphoto.setImageDrawable(photo_drawable);

}

public Drawable loadImagefromurl(Bitmap icon)
{
    Drawable d=new BitmapDrawable(icon);
    return d;
}

public class GetImages extends AsyncTask<Void, Void, Void>
{
    public ProgressDialog progDialog=null;

    protected void onPreExecute()
    {
        progDialog=ProgressDialog.show(context, "", "Loading...",true);
    }
    @Override
    protected Void doInBackground(Void... params)
    {

        Bitmap bitmap = BitmapFactory.decodeFile(photo_url.toString().trim());
        bitmap = Bitmap.createScaledBitmap(bitmap,500, 500, true);
        Drawable d=loadImagefromurl(bitmap);
        photo_drawable = d;


        return null;
    }

    protected void onPostExecute(Void result)
    {
        if(progDialog.isShowing())
        {
            progDialog.dismiss();
        }
        updateImageTable();
    }
}