2014-12-18 2 views
1

В моем приложении пользователь может взять изображение из намерения камеры, а затем я хочу вернуть это изображение в виде изображения. Как я могу это сделать?Как я могу установить изображение, взятое из намерения камеры, в ImageView?

Вот моя камера Намерение:

Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); 
startActivityForResult(intent, TAKE_PICTURE); 

И onActivityResult

protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    { 
     //Check that request code matches ours: 
     if (requestCode == TAKE_PICTURE) 
     { 
      //Check if your application folder exists in the external storage, if not create it: 
      File imageStorageFolder = new File(Environment.getExternalStorageDirectory()+File.separator+"Kruger National Park"); 
      if (!imageStorageFolder.exists()) 
      { 
       imageStorageFolder.mkdirs(); 
       Log.d(TAG , "Folder created at: "+imageStorageFolder.toString()); 
      } 

      //Check if data in not null and extract the Bitmap: 
      if (data != null) 
      { 
       String filename = "image"; 
       String fileNameExtension = ".jpg"; 
       File sdCard = Environment.getExternalStorageDirectory(); 
       String imageStorageFolder1 = File.separator+"Kruger National Park"+File.separator; 
       File destinationFile = new File(sdCard, imageStorageFolder1 + filename + fileNameExtension); 
       Log.d(TAG, "the destination for image file is: " + destinationFile); 
       if (data.getExtras() != null) 
       { 
        Bitmap bitmap = (Bitmap)data.getExtras().get("data"); 
        try 
        { 
         FileOutputStream out = new FileOutputStream(destinationFile); 
         bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); 
         out.flush(); 
         out.close(); 
        } 
        catch (Exception e) 
        { 
         Log.e(TAG, "ERROR:" + e.toString()); 
        } 

Это все работает, но просто хочу, чтобы добавить его сейчас к моему ImageView:

ImageView image = (ImageView) v.findViewById(R.id.imageV); 
     image.setImageResource(); 

Может кто-то пожалуйста, Помогите?

ответ

1

Вот пример активности, который запустит приложение камеры, а затем извлечет изображение и отобразит его.

package edu.gvsu.cis.masl.camerademo; 

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

public class MyCameraActivity extends Activity { 
private static final int CAMERA_REQUEST = 1888; 
private ImageView imageView; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    this.imageView = (ImageView)this.findViewById(R.id.imageView1); 
    Button photoButton = (Button) this.findViewById(R.id.button1); 
    photoButton.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      Intent cameraIntent = new  Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
      startActivityForResult(cameraIntent, CAMERA_REQUEST); 
     } 
    }); 
} 

protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) { 
     Bitmap photo = (Bitmap) data.getExtras().get("data"); 
     imageView.setImageBitmap(photo); 
    } 
} 

} Обратите внимание, что само приложение камеры дает возможность просмотра/пересдать изображение, а когда изображение будет принято, деятельность отображает его.

Вот макет, который использует вышеуказанная деятельность. Это просто LinearLayout содержащего кнопки с идентификатором button1 и ImageView с идентификатором imageview1:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
> 
<Button android:id="@+id/button1" android:layout_width="wrap_content"  android:layout_height="wrap_content" android:text="@string/photo"></Button> 
<ImageView android:id="@+id/imageView1" android:layout_height="wrap_content"  android:src="@drawable/icon" android:layout_width="wrap_content"></ImageView> 

</LinearLayout> 

И одной последней деталью, не забудьте добавить:

<uses-feature android:name="android.hardware.camera"></uses-feature> 

и если камера не является обязательной для вашего приложения функциональность. убедитесь, что в запросе установлено значение false. например

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

к вашему manifest.xml.

0

Вы имеете в виду это?

image.setImageBitmap(bitmap); 

Чтобы повернуть растровое изображение обратно в исходную ориентацию, вы можете использовать следующий код.

 ExifInterface exif = new ExifInterface(path); 
     int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); 

     int angle = 0; 

     if (orientation == ExifInterface.ORIENTATION_ROTATE_90) 
      angle = 90; 
     else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) 
      angle = 180; 
     else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) 
      angle = 270; 

     Matrix mat = new Matrix(); 
     mat.postRotate(angle); 
     Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight, mat, true); 

Строка «путь» здесь - путь к файлу, в котором была сохранена фотография. Это единственный код, который я имею в настоящее время для этой проблемы. Я надеюсь, что это поможет вам. Что может быть интересно в этом случае, так это то, что вы также можете предоставить файл намерению. Фотография будет сохранена в этом файле.

intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destinationFile)); 
+0

Спасибо, что сработал !! однако у меня сейчас странная проблема, если я возьму изображение в портрете, оно вернется в качестве пейзажной миниатюры? – Newbie

+0

@Newbie Проверьте отредактированный ответ. –

Смежные вопросы