2013-10-08 14 views
1

嗨,我使用我的攝像頭模擬攝像機在模擬器中,當我去拍照,然後選擇複選標記按鈕,使用我碰到一個運行圖片而試圖錯誤顯示圖像回到我的ImageView上的應用程序。獲取圖像和比ImageView的內顯示 - Android電子

這裏是我的代碼:

發起者:

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
       startActivityForResult(takePictureIntent, CAMERA_PIC_REQUEST); 

功能....

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
if (requestCode == CAMERA_PIC_REQUEST) { 
       if (resultCode == RESULT_OK) { 
        Uri selectedImageUri = data.getData(); 

        //OI FILE Manager 
       filemanagerstring = selectedImageUri.getPath(); 

        //MEDIA GALLERY 
       selectedImagePath = getPath(selectedImageUri); 


       img.setImageURI(selectedImageUri); 

       imagePath.getBytes(); 

       Bitmap bm = BitmapFactory.decodeFile(imagePath); 

       Log.w("Here","error"); 

       Bitmap bm = BitmapFactory.decodeFile(imagePath); 

       ImageView image = (ImageView) findViewById(R.id.gimg1); 
       image.setImageBitmap(bm); 
      } else if (resultCode == RESULT_CANCELED){ 

      } 
    } 
} 

我跑跨runtime error

建議和需要的想法!

+0

剛剛更新的功能,包括其中的數據是來自....等待日誌 –

回答

1
if(requestCode==CAMERA_PIC_REQUEST && resultCode==RESULT_OK){ 

     Bitmap image = (Bitmap) data.getExtra("data"); 
     image_taken.setImageBitmap(image); 
} 

你分別致電data.getData(),而這應該是data.getExtra("data")作爲dataintent,你將不得不把bitmap

+0

偉大的工作:) –

1
if(requestCode==CAMERA_PIC_REQUEST && resultCode==RESULT_OK){ 

     Bitmap image = (Bitmap) data.getExtras().get("data"); 

     ImageView image = (ImageView) findViewById(R.id.gimg1); 

     image.setImageBitmap(image); 
} 
2

您可以使用下面的代碼。它是全功能,並允許您設置您的相機和畫廊都映像。我幾乎可以肯定,你的運行時錯誤是「的OutOfMemoryError:位圖大小超過VM預算」,因爲我看到你已經直接加載捕獲的圖像到您的ImageView。您應該對其進行縮放,請看看我下面的代碼稱爲GetScaledBitmap的方法。希望如果您使用的方法,只有當你的圖像加載到您的ImageView您的代碼將工作正常。完整的例子爲你完成,希望它有幫助。

package com.tseg.android.mctemplate; 

import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.InputStream; 
import java.text.SimpleDateFormat; 
import java.util.ArrayList; 
import java.util.Date; 

import android.app.Activity; 
import android.app.AlertDialog; 
import android.content.ContentResolver; 
import android.content.ContentValues; 
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.provider.MediaStore.Images; 
import android.util.Log; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.ImageView; 
import android.widget.Toast; 
import com.tseg.android.mctemplate.R; 

public class PhotoTake extends Activity { 
    Button add1 ; 
    ImageView img1 ; 
    private static final int ACTIVITY_PHOTOS = 0; 
    private static final String PACKAGE = "spine"; 

    Uri mCapturedImageURI; 

    private int photo_count = 0; 
    boolean hasPhotos = false; 
    Bitmap bitmap; 
    String[] paths; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.photo); 

     add1 = (Button) findViewById(R.id.add1); 
     img1 = (ImageView) findViewById(R.id.img1); 

     add1.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 
       ShowDialog(100, 1000); 
      } 
     }); 
    } 



    void ShowDialog(final int req, final int choose) { 
     AlertDialog.Builder builder = new AlertDialog.Builder(this); 
     builder.setMessage(""); 
     builder.setTitle("Select Photo") 
       .setCancelable(false) 
       .setNegativeButton("Take Photo", 
         new DialogInterface.OnClickListener() { 

          public void onClick(DialogInterface dialog, 
            int which) {         
           File pictureFileDir = getDir(); 
           if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) { 

            Log.d("Photo Take", "Can't create directory to save image."); 
            Toast.makeText(PhotoTake.this , "Can't create directory to save image.", 
              Toast.LENGTH_LONG).show(); 
            return; 
           } 

           SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss"); 
           String date = dateFormat.format(new Date()); 
           String photoFile = "Picture_" + date + ".jpg"; 
           String filepath = pictureFileDir.getPath() + File.separator; 
           File imageFile = new File(filepath , photoFile); 

           ContentValues image = new ContentValues(); 

           image.put(Images.Media.TITLE, photoFile); 
           image.put(Images.Media.DISPLAY_NAME, photoFile); 
           image.put(Images.Media.DESCRIPTION, "Accident data Accachment " + date); 
           image.put(Images.Media.DATE_ADDED, date); 
           image.put(Images.Media.DATE_TAKEN, date); 
           image.put(Images.Media.DATE_MODIFIED, date); 
           image.put(Images.Media.MIME_TYPE, "image/jpeg"); 
           image.put(Images.Media.ORIENTATION, 0); 

           File parent = imageFile.getParentFile(); 
           String path = parent.toString().toLowerCase(); 
           String name = parent.getName().toLowerCase(); 
           image.put(Images.ImageColumns.BUCKET_ID, path.hashCode()); 
           image.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, name); 
           image.put(Images.Media.SIZE, imageFile.length()); 

           image.put(Images.Media.DATA, imageFile.getAbsolutePath()); 

           mCapturedImageURI = PhotoTake.this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, image); 


           Intent intent = new Intent(
             MediaStore.ACTION_IMAGE_CAPTURE); 
           intent.putExtra(MediaStore.EXTRA_OUTPUT, 
             mCapturedImageURI); 

           startActivityForResult(intent, req); 

          } 
         }) 
       .setPositiveButton("Choose Existing", 
         new DialogInterface.OnClickListener() { 
          public void onClick(DialogInterface dialog, int id) { 
           Intent intent = new Intent(); 
           intent.setType("image/*"); 
           intent.setAction(Intent.ACTION_GET_CONTENT); 

           startActivityForResult(Intent.createChooser(
             intent, "Complete action using"), 
             choose); 
          } 
         }); 
     AlertDialog alert = builder.create(); 
     alert.show(); 
    } 

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

     // From camera 

     if (requestCode == 100 && resultCode == Activity.RESULT_OK) { 
      if (mCapturedImageURI != null) { 
       img1.setImageBitmap(getScaledBitmap(mCapturedImageURI));; 
       System.out.println("Onactivity Result uri = " + mCapturedImageURI.toString()); 
      } else { 
       Toast.makeText(PhotoTake.this, "Error getting Image", 
         Toast.LENGTH_SHORT).show(); 
      } 

     } 

     //From gallery 
     if (requestCode == 1000) { 
      if (resultCode == Activity.RESULT_OK) { 
       Uri selectedImage = data.getData(); 
       System.out.println("Content Path : " + selectedImage.toString()); 

       if (selectedImage != null) { 
        img1.setImageBitmap(getScaledBitmap(selectedImage)); 
       } else { 
        Toast.makeText(PhotoTake.this, "Error getting Image", 
          Toast.LENGTH_SHORT).show(); 
       }   
      } else if (resultCode == Activity.RESULT_CANCELED) { 
       Toast.makeText(PhotoTake.this, "No Photo Selected", 
         Toast.LENGTH_SHORT).show(); 
      } 
     } 

    } 

    public Bitmap getBitmap(String path) { 
     Bitmap myBitmap = null; 
     File imgFile = new File(path); 
     if (imgFile.exists()) { 
      myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath()); 
     } 
     return myBitmap; 
    } 


    public String getPath(Uri photoUri) { 

     String filePath = ""; 
     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]); 
      filePath = cursor.getString(columnIndex); 
      cursor.close(); 
     } 
     return filePath; 
    } 

    private File getDir() { 
     File sdDir = Environment 
      .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); 
     return new File(sdDir, "SpineAttachments"); 
    } 

    private Bitmap getScaledBitmap(Uri uri){ 
     Bitmap thumb = null ; 
     try { 
      ContentResolver cr = getContentResolver(); 
      InputStream in = cr.openInputStream(uri); 
      BitmapFactory.Options options = new BitmapFactory.Options(); 
      options.inSampleSize=8; 
      thumb = BitmapFactory.decodeStream(in,null,options); 
     } catch (FileNotFoundException e) { 
      Toast.makeText(PhotoTake.this , "File not found" , Toast.LENGTH_SHORT).show(); 
     } 
     return thumb ; 
    } 
} 
+0

雅以上建議偉大的工作,絕對欣賞你的代碼:) –

+1

聽起來很棒! ! :) – ayon

0

非常簡單的方法來點擊按鈕並在imageview中設置存儲圖像。

`public class MainActivity extends Activity {

private static final int CAMERA_PIC_REQUEST = 22; 

Uri cameraUri; 

Button BtnSelectImage; 
private ImageView ImgPhoto; 
private String Camerapath ; 



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

    ImgPhoto = (ImageView) findViewById(R.id.imageView1); 

    BtnSelectImage = (Button) findViewById(R.id.button1); 
    BtnSelectImage.setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      // TODO Auto-generated method stub 
      try { 
        Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
        startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST); 
      } catch (Exception e) { 
       Toast.makeText(getApplicationContext(), "Couldn't load photo", Toast.LENGTH_LONG).show(); 
      } 
     } 
    }); 

} 


@Override 
public void onActivityResult(final int requestCode, int resultCode, Intent data) { 
    try { 
     switch (requestCode) { 
     case CAMERA_PIC_REQUEST: 
      if (resultCode == RESULT_OK) { 
       try { 
         Bitmap photo = (Bitmap) data.getExtras().get("data"); 

         ImgPhoto.setImageBitmap(photo);  

       } catch (Exception e) { 
        Toast.makeText(this, "Couldn't load photo", Toast.LENGTH_LONG).show(); 
       } 
      } 
      break; 
      default: 
      break; 
     } 
    } catch (Exception e) { 
    } 
} 

}`

設置此清單。

<uses-permission android:name="android.permission.CAMERA" /> <uses-feature android:name="android.hardware.camera" android:required="false"></uses-feature>