2015-04-29 42 views
-1

我的Java類代碼有一個Button,它允許用戶訪問攝像頭,拍照,然後將該圖片添加到ImageView。
我未能實現此功能。如何將相機中的圖片添加到Android中的ImageView中?

這裏是我的Java代碼:

package com.example.vikingpianomovers; 

import java.io.File; 
import java.io.IOException; 
import java.sql.Date; 
import java.text.SimpleDateFormat; 
import android.app.Activity; 
import android.content.Intent; 
import android.graphics.Bitmap; 
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.EditText; 
import android.widget.ImageView; 
import android.widget.LinearLayout; 
import android.widget.Spinner; 


public class QuoteFormActivity extends Activity { 


String mCurrentPhotoPath; 
protected static final int MEDIA_TYPE_IMAGE = 1111; 
protected static final String IMAGE_DIRECTORY_NAME = null; 
private static final int RESULT_OK = 1; 
private static final int REQUEST_IMAGE_CAPTURE = 0; 
private static final int REQUEST_TAKE_PHOTO = 0; 
ImageView mImageView = null; 


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


    final EditText name = (EditText) findViewById(R.id.EditTextName); 
    final EditText emailAddress = (EditText) findViewById(R.id.EditTextEmail); 
    final EditText phoneNumber = (EditText) findViewById(R.id.EditPhoneNumber); 
    final EditText makeModel = (EditText) findViewById(R.id.EditTextMakeModel); 
    final EditText pianoSize = (EditText) findViewById(R.id.EditTextPianoSize); 
    final Spinner measurementUnit = (Spinner) findViewById(R.id.spinner2); 
    final EditText cityOrigin = (EditText) findViewById(R.id.EditTextCityOrigin); 
    final EditText cityDest = (EditText) findViewById(R.id.EditTextCityDest); 
    final EditText stairs = (EditText) findViewById(R.id.EditTextStairs); 
    final ImageView mImageView = (ImageView) findViewById(R.id.attachedImage1); 
    final ImageView mImageView2 = (ImageView) findViewById(R.id.attachedImage2); 

    //button that starts the camera 
    Button addPic = (Button) findViewById(R.id.attachPicButton); 
    addPic.setOnClickListener(new View.OnClickListener(){ 

     @Override 
     public void onClick(View v) { 
      //button click invokes method to start camera 
      dispatchTakePictureIntent(); 
     } 

    }); 

    //button that sends data from form to user's email 
    Button email = (Button) findViewById(R.id.SubmitButton); 
    email.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      //intent to send email 

      Intent email = new Intent(android.content.Intent.ACTION_SEND); 

      email.setType("plain/text"); 
      email.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"[email protected]"}); 
      email.putExtra(android.content.Intent.EXTRA_SUBJECT, "Viking Android App Submission"); 
      email.putExtra(android.content.Intent.EXTRA_TEXT, 
        "name: " + name.getText().toString() + '\n' + '\n' + 
        "Email Address: " + emailAddress.getText().toString()+ '\n' + '\n' + 
        "Phone Number: " + phoneNumber.getText().toString() + '\n' + '\n' + 
        "Make and Model: " + makeModel.getText().toString() + '\n' + '\n' + 
        "Piano Size: " + pianoSize.getText().toString()+ '\n' + '\n' + 
        "City of Origin: " + cityOrigin.getText().toString() + '\n' + '\n' + 
        "City Destination: " + cityDest.getText().toString() + '\n' + '\n' + 
        "Number of stairs: " + stairs.getText().toString() + '\n' + '\n' + 
        "Pic(s): " + mImageView 
        ); 
      startActivity(Intent.createChooser(email, "Send mail...")); 
     } 
    }); 

    //layout params for LinearLayout 
    LinearLayout.LayoutParams layoutParams= new LinearLayout.LayoutParams(
      LinearLayout.LayoutParams.MATCH_PARENT, 
      LinearLayout.LayoutParams.MATCH_PARENT); 

    //Create a new LinearLayout 
    LinearLayout layout = new LinearLayout(this); 
    layout.setOrientation(LinearLayout.VERTICAL); 
    layout.setLayoutParams(layoutParams); 

    new LinearLayout.LayoutParams(
      LinearLayout.LayoutParams.WRAP_CONTENT, 
      LinearLayout.LayoutParams.WRAP_CONTENT); 
} 

@Override 
//result of dispatchTakePictureIntent 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) { 
     Bundle extras = data.getExtras(); 
     Bitmap imageBitmap = (Bitmap) extras.get("data"); 
     mImageView.setImageBitmap(imageBitmap); 
    } 
} 

//method to create image file in external directory 
private File createImageFile() throws IOException { 
    // Create an image file name 
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date(0)); 
    String imageFileName = "JPEG_" + timeStamp + "_"; 
    File storageDir = Environment.getExternalStoragePublicDirectory(
      Environment.DIRECTORY_PICTURES); 
    File image = File.createTempFile(
     imageFileName, /* prefix */ 
     ".jpg",   /* suffix */ 
     storageDir  /* directory */ 
    ); 

    // Save a file: path for use with ACTION_VIEW intents 
    mCurrentPhotoPath = "file:" + image.getAbsolutePath(); 
    return image; 
} 

//method containing intent to access camera and create image file 
private void dispatchTakePictureIntent() { 
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
    // Ensure that there's a camera activity to handle the intent 
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) { 
     // Create the File where the photo should go 
     File photoFile = null; 
     try { 
      photoFile = createImageFile(); 
     } catch (IOException ex) { 
      // Error occurred while creating the File 
      Log.i("photoFile not created", mCurrentPhotoPath); 
     } 
     // Continue only if the File was successfully created 
     if (photoFile != null) { 
      takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, 
        Uri.fromFile(photoFile)); 
      startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO); 
     } 
    } 
} 

public QuoteFormActivity() { 
    // TODO Auto-generated constructor stub 
} 
} 

這裏是我的xml:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="wrap_content"> 

<LinearLayout 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:orientation="vertical" > 

<ImageView 
    android:id="@+id/imageView1" 
    android:layout_width="wrap_content" 
    android:layout_height="175dp" 
    android:layout_marginTop="2dp" 
    android:cropToPadding="false" 
    android:paddingBottom="0dp" 
    android:paddingLeft="10dp" 
    android:paddingRight="10dp" 
    android:src="@drawable/vikingmobilequotelogo" /> 

<EditText 
    android:id="@+id/EditTextName" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:hint="@string/namehint" 
    android:inputType="textPersonName" 
    android:padding="10dp" > 
</EditText> 

<EditText 
    android:id="@+id/EditTextEmail" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:hint="@string/emailhint" 
    android:inputType="textEmailAddress" 
    android:padding="10dp" > 
</EditText> 

<EditText 
    android:id="@+id/EditPhoneNumber" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:hint="@string/phonenumberhint" 
    android:inputType="phone" 
    android:padding="10dp" > 
</EditText> 

<EditText 
    android:id="@+id/SpinnerTextView" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:inputType="text" 
    android:hint="@string/piano_type" 
    android:textSize="18sp" 
    android:padding="10dp"> 
</EditText> 

<EditText 
    android:id="@+id/EditTextMakeModel" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:hint="@string/piano_make_model_hint" 
    android:inputType="text" 
    android:padding="10dp" > 
</EditText> 

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal" 
    android:padding="0dp" > 

<EditText 
    android:id="@+id/EditTextPianoSize" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:hint="@string/piano_size_hint" 
    android:inputType="number" 
    android:layout_weight="1" 
    android:padding="10dp"> 
</EditText> 

<Spinner 
    android:id="@+id/spinner2" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_weight="5" 
    android:entries="@array/piano_measurement_type" 
    android:prompt="@string/piano_type_prompt" > 
    </Spinner> 
</LinearLayout> 

<EditText 
    android:id="@+id/EditTextCityOrigin" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:hint="@string/origin_hint" 
    android:padding="10dp"> 
</EditText> 

<EditText 
    android:id="@+id/EditTextCityDest" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:hint="@string/dest_hint" 
    android:padding="10dp"> 
</EditText> 

<EditText 
    android:id="@+id/EditTextStairs" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:hint="@string/stairs_hint" 
    android:padding="10dp"> 
</EditText> 

<LinearLayout 
    android:orientation="horizontal" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:padding="5dp"> 

    <TextView 
     android:id="@+id/TextViewSubmit" 
     android:layout_width="150dp" 
     android:layout_height="wrap_content" 
     android:padding="10dp" 
     android:text="@string/submit_text" 
     android:textSize="18sp" > 
    </TextView> 

    <Button 
     android:id="@+id/attachPicButton" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_marginTop="10dp" 
     android:padding="10dp" 
     android:text="@string/picButton" > 
    </Button> 
</LinearLayout> 

<LinearLayout 
    android:orientation="horizontal" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:padding="5dp"> 

<ImageView 
    android:id="@+id/attachedImage1" 
    android:layout_width="150dp" 
    android:layout_height="150dp" 
    android:src="@drawable/ic_launcher" >" 
</ImageView> 

<ImageView 
    android:id="@+id/attachedImage2" 
    android:layout_width="150dp" 
    android:layout_height="150dp" 
    android:src="@drawable/ic_launcher" > 
</ImageView> 
</LinearLayout> 

<Button 
    android:id="@+id/SubmitButton" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/submit_button_text" 
    android:padding="10dp" 
    android:layout_marginTop="20dp" 
    android:layout_marginBottom="10dp" > 
</Button> 

清單:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
package="com.example.vikingpianomovers" 
android:versionCode="1" 
android:versionName="1.0" > 

<uses-sdk 
    android:minSdkVersion="8" 
    android:targetSdkVersion="22" /> 

<application 
    android:allowBackup="true" 
    android:icon="@drawable/viking_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 
    <activity 
     android:name="MainActivity" 
     android:label="@string/app_name"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 
      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
    <activity 
     android:label="@string/app_name" 
     android:name="QuoteFormActivity"> 
     <intent-filter > 
      <action android:name="android.intent.action.MAIN"/> 
      <category android:name="android.intent.category.LAUNCHER"/> 
     </intent-filter> 
    </activity> 
</application> 
    <uses-feature android:name="android.hardware.camera" /> 
    <uses-permission android:name="android.permission.camera" /> 
    <uses-permission android:name="android.permission.DIAL_PHONE"></uses-permission> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> 

+0

sir你是否搜索過你的問題的stackoverflow? – Elltz

+0

是的,刻苦。因爲在我想通過所有搜索找到後,我無法弄清楚這一點,所以我會發布我的代碼以查看發生了什麼。 –

+0

[從攝像頭獲取圖片到ImageView Android]可能的重複(http://stackoverflow.com/questions/15799307/get-image-from-camera-into-imageview-android) – jlopez

回答

0

使用本

@Override 
//result of dispatchTakePictureIntent 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) { 
    mImageView.setImageBitmap(new BitmapDrawable(getBaseContext(), 
         getPath(data.getData(),getBaseContext()))); 
    } 
} 

添加這個方法太

public String getPath(Uri uri,Context c) { 
    String[] projection = { MediaStore.Images.Media.DATA }; 
    Cursor cursor = c.getContentResolver().query(uri, projection, null, null, null); 
    if (cursor == null) 
     return null; 
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
    cursor.moveToFirst(); 
    String s=cursor.getString(column_index); 
    cursor.close(); 
    return s; 
} 

先生,這個問題的答案是對計算器洙許多問題重複,我不知道你,但如果你沒問題,然後這個答案解決了你的問題不接受它並刪除了問題,所以幫助清理網站,畢竟你的問題已經解決了

相關問題