0

我正在寫一個應用程序,我需要把圖像視圖中的哪個用戶必須通過單擊它來加載圖像。點擊後我可以選擇讓用戶選擇是從電話本身加載存儲的圖像還是從相機中取出新的圖像。Android - 如何把從SD卡或相機膠捲加載圖像的imageview?

這個問題可能是多餘的,但幾乎沒有任何類似的問題/問題在這裏顯示沒有達到我想要做的。

P.s.我正在使用安裝了Eclipse 4.2(JUNO)SDK的Android API15。

這裏是主要活動的代碼片段,給了我一個錯誤:

package test.imgbyte.conerter; 

import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 

import android.net.Uri; 
import android.app.Activity; 
import android.content.Intent; 
import android.graphics.Bitmap; 
import android.os.Bundle; 
import android.widget.Button; 
import android.widget.ImageView; 
import android.view.View; 

public class FindImgPathActivity extends Activity 
{ 

     private Uri mImageCaptureUri; 
     static final int CAMERA_PIC_REQUEST = 1337; 

     public void onCreate(Bundle savedInstanceState) 
     { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.imgfilepath); 

     Button camera = (Button) findViewById(R.id.btnLoad); 
     camera.setOnClickListener(new View.OnClickListener() 
     { 
      public void onClick(View v) 
      { 
       Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
       cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri); 
       startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);    
      }    
     }); 

     } 
    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    { 
     super.onActivityResult(requestCode, resultCode, data); 
     if (requestCode == CAMERA_PIC_REQUEST) 
     { 
      Bitmap thumbnail = (Bitmap) data.getExtras().get("data"); 
      ImageView image = (ImageView) findViewById(R.id.imgLoaded); 
      image.setImageBitmap(thumbnail); 

      String pathToImage = mImageCaptureUri.getPath(); 

      // pathToImage is a path you need. 

      // If image file is not in there, 
      // you can save it yourself manually with this code: 
      File file = new File(pathToImage); 

      FileOutputStream fOut; 
      try 
      { 
       fOut = new FileOutputStream(file); 
       thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, fOut); // You can choose any format you want 
      } 
      catch (FileNotFoundException e) 
      { 
       e.printStackTrace(); 
      } 

     } 
    }  
} 

錯誤我得到的是這樣的,從logcat的:

11-05 19:23:11.777: E/AndroidRuntime(1206): FATAL EXCEPTION: main 
11-05 19:23:11.777: E/AndroidRuntime(1206): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1337, result=-1, data=Intent { act=inline-data (has extras) }} to activity {test.imgbyte.conerter/test.imgbyte.conerter.FindImgPathActivity}: java.lang.NullPointerException 
+0

我認爲你可以在這裏參考答案:[http://stackoverflow.com/questions/2507898/how-to-pick-an-image-from-gallery- SD卡換我的應用程序內功能於Android的RQ = 1] [1] [1]:http://stackoverflow.com/questions/2507898/how-to-pick-an -image-from-gallery-sd-card-for-my-app-in-android?rq = 1 –

回答

4

啊。這個錯誤。我花了很多年解讀它的含義,顯然結果有一些你試圖訪問的空字段。在你的情況下,它是你沒有真正用文件初始化的mImageCaptureUri字段。啓動相機意圖的方法是創建一個文件,並將它的Uri作爲EXTRA_OUTPUT傳遞給intent。

File tempFile = new File("blah.jpg"); 
... 
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile)); 
... 

然後,您可以使用file.getAbsolutePath()方法來加載位圖。

鑑於我們在這一點上,讓我與大家分享我上週學到的關於直接加載Bitmap的非常重要的一點......不要這麼做!我花了一個星期才明白爲什麼,當我做了我無法相信我以前不明白的事情時,這一切都只是一場記憶。

使用此代碼可以有效地加載位圖。 (一旦你的文件,只是使用file.getAbsolutePath()在BitmapFactory.decodeFile()):

public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { 
     // Raw height and width of image 
     final int height = options.outHeight; 
     final int width = options.outWidth; 
     int inSampleSize = 1; 

     if (height > reqHeight || width > reqWidth) { 
      if (width > height) { 
       inSampleSize = Math.round((float)height/(float)reqHeight); 
      } else { 
       inSampleSize = Math.round((float)width/(float)reqWidth); 
      } 
     } 
     return inSampleSize; 
    } 

    public static Bitmap decodeSampledBitmapFromPath(String path, int reqWidth, int reqHeight) { 

     // First decode with inJustDecodeBounds=true to check dimensions 
     final BitmapFactory.Options options = new BitmapFactory.Options(); 
     options.inJustDecodeBounds = true; 
     BitmapFactory.decodeFile(path, options); 

     // Calculate inSampleSize 
     options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 

     // Decode bitmap with inSampleSize set 
     options.inJustDecodeBounds = false; 
     return BitmapFactory.decodeFile(path, options); 
    } 

只需將您的file.getAbsolutePath()作爲第一個參數,與所需的寬度和高度,以沿decodeSampledBitmapFromPath函數來獲得一個有效的加載位圖。此代碼已從Android文檔的version here中修改。

編輯:

private Uri mImageCaptureUri; // This needs to be initialized. 
     static final int CAMERA_PIC_REQUEST = 1337; 
private String filePath; 

     public void onCreate(Bundle savedInstanceState) 
     { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.imgfilepath); 
// Just a temporary solution, you're supposed to load whichever directory you need here 
     File mediaFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Temp1.jpg"); 
filePath = mediaFile.getABsolutePath(); 

     Button camera = (Button) findViewById(R.id.btnLoad); 
     camera.setOnClickListener(new View.OnClickListener() 
     { 
      public void onClick(View v) 
      { 
       Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
       cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(mediaFile)); 
       startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);    
      }    
     }); 

     } 
    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    { 
     super.onActivityResult(requestCode, resultCode, data); 
     if (requestCode == CAMERA_PIC_REQUEST) 
     { 
      if(resultCode == RESULT_OK) 
      { 
int THUMBNAIL_SIZE = 64; 
// Rest assured, if the result is OK, you're file is at that location 
      Bitmap thumbnail = decodeSampledBitmapFromPath(filePath, THUMBNAIL_SIZE, THUMBNAIL_SIZE); // This assumes you've included the method I mentioned above for optimization 
      ImageView image = (ImageView) findViewById(R.id.imgLoaded); 
      image.setImageBitmap(thumbnail); 
      } 
    }  
} 
+0

你會推薦我的代碼的編輯片段插入你的建議嗎?我非常感謝,因爲作爲Android平臺上的初學者,atm讓我習慣於解決即將遇到的問題的解決方案。 –

+0

我已經添加了內聯代碼。爲了更好地理解所有這些,請仔細閱讀文檔,當我遇到這個問題時,我花了3天的時間詳盡地閱讀了文檔,這些文檔讓我受益匪淺,並教會了我很多。乾杯。 – varevarao

相關問題