2015-12-21 79 views
2

在我的活动中,我想从相机或图库中放入一张ImageView照片!从参考我们得到这个代码imageview从相机或画廊加载图像

private void selectImage() { 
    final CharSequence[] items = { "Take Photo", "Choose from Library", 
      "Cancel" }; 

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); 
    builder.setTitle("Add Photo!"); 
    builder.setItems(items, new DialogInterface.OnClickListener() { 
     @Override 
     public void onClick(DialogInterface dialog, int item) { 
      if (items[item].equals("Take Photo")) { 
       Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
       startActivityForResult(intent, REQUEST_CAMERA); 
      } else if (items[item].equals("Choose from Library")) { 
       Intent intent = new Intent(
         Intent.ACTION_PICK, 
         android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
       intent.setType("image/*"); 
       startActivityForResult(
         Intent.createChooser(intent, "Select File"), 
         SELECT_FILE); 
      } else if (items[item].equals("Cancel")) { 
       dialog.dismiss(); 
      } 
     } 
    }); 
    builder.show(); 
} 

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

    if (resultCode == Activity.RESULT_OK) { 
     if (requestCode == SELECT_FILE) 
      onSelectFromGalleryResult(data); 
     else if (requestCode == REQUEST_CAMERA) 
      onCaptureImageResult(data); 
    } 
} 

private void onCaptureImageResult(Intent data) { 
    Bitmap thumbnail = (Bitmap) data.getExtras().get("data"); 
    ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
    thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes); 

    File destination = new File(Environment.getExternalStorageDirectory(), 
      System.currentTimeMillis() + ".jpg"); 

    FileOutputStream fo; 
    try { 
     destination.createNewFile(); 
     fo = new FileOutputStream(destination); 
     fo.write(bytes.toByteArray()); 
     fo.close(); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    ivImage.setImageBitmap(thumbnail); 
} 

@SuppressWarnings("deprecation") 
private void onSelectFromGalleryResult(Intent data) { 
    Uri selectedImageUri = data.getData(); 
    String[] projection = { MediaColumns.DATA }; 
    Cursor cursor = managedQuery(selectedImageUri, projection, null, null, 
      null); 
    int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA); 
    cursor.moveToFirst(); 

    String selectedImagePath = cursor.getString(column_index); 

    Bitmap bm; 
    BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 
    BitmapFactory.decodeFile(selectedImagePath, options); 
    final int REQUIRED_SIZE = 200; 
    int scale = 1; 
    while (options.outWidth/scale/2 >= REQUIRED_SIZE 
      && options.outHeight/scale/2 >= REQUIRED_SIZE) 
     scale *= 2; 
    options.inSampleSize = scale; 
    options.inJustDecodeBounds = false; 
    bm = BitmapFactory.decodeFile(selectedImagePath, options); 

    ivImage.setImageBitmap(bm); 
} 

但我在这段代码中有错误。当我在照相机或画廊点击addphoto按钮内它显示

W/InputEventReceiver:试图完成的输入事件,但该输入 事件接收器已经被设置。

它不会显示在imageview的捕获图像和活动转移到主activity.Anyone告诉什么发生这种方法,以及如何解决这个

+0

我认为你应该在这个代码中的错误发生在移动的onCaptureImageResult代码(..)的异步任务或线程(可以使用postDelay(..)) – GiapLee

回答

3

试试这个这里imgPic是ImageView的

private void selectImage() { 
    final CharSequence[] options = { "Take Photo", "Gallery" }; 

    AlertDialog.Builder builder = new AlertDialog.Builder(
      EditProfileActivity.this); 
    builder.setItems(options, new DialogInterface.OnClickListener() { 
     @Override 
     public void onClick(DialogInterface dialog, int item) { 
      if (options[item].equals("Take Photo")) { 
       Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
       File f = new File(android.os.Environment 
         .getExternalStorageDirectory(), "temp.jpg"); 
       intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f)); 
       startActivityForResult(intent, 1); 
      } else if (options[item].equals("Gallery")) { 
       Intent intent = new Intent(
         Intent.ACTION_PICK, 
         android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
       startActivityForResult(intent, 2); 

      } 
     } 
    }); 
    builder.show(); 
} 

在ActivityResult

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

    super.onActivityResult(requestCode, resultCode, data); 
    if (resultCode == RESULT_OK) { 
     if (requestCode == 1) { 
      // onCaptureImageResult(data); 
      try { 

       File f = new File(Environment.getExternalStorageDirectory() 
        .toString()); 
       for (File temp : f.listFiles()) { 
        if (temp.getName().equals("temp.jpg")) { 
         f = temp; 
         break; 
        } 
       } 
       Bitmap bitmap; 
       BitmapFactory.Options bitmapOptions = new BitmapFactory.Options(); 

       bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(), 
         bitmapOptions); 
       imgPic.setImageBitmap(bitmap); 

       String path = android.os.Environment 
         .getExternalStorageDirectory() 
         + File.separator 
         + "Phoenix" + File.separator + "default"; 
       f.delete(); 
       OutputStream outFile = null; 
       File file = new File(path, String.valueOf(System 
         .currentTimeMillis()) + ".jpg"); 
       try { 
        outFile = new FileOutputStream(file); 
        bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile); 
        outFile.flush(); 
        outFile.close(); 
       } catch (FileNotFoundException e) { 
        e.printStackTrace(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 

      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } else if (requestCode == 2) { 

      onSelectFromGalleryResult(data); 
     } 
    } 
} 

onSelectFromGalleryResult

private void onSelectFromGalleryResult(Intent data) { 
    Uri selectedImageUri = data.getData(); 
    String[] projection = { MediaColumns.DATA }; 
    @SuppressWarnings("deprecation") 
    Cursor cursor = managedQuery(selectedImageUri, projection, null, null, 
      null); 
    int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA); 
    cursor.moveToFirst(); 

    String selectedImagePath = cursor.getString(column_index); 

    Bitmap bm; 
    BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 
    BitmapFactory.decodeFile(selectedImagePath, options); 
    final int REQUIRED_SIZE = 200; 
    int scale = 1; 
    while (options.outWidth/scale/2 >= REQUIRED_SIZE 
      && options.outHeight/scale/2 >= REQUIRED_SIZE) 
     scale *= 2; 
    options.inSampleSize = scale; 
    options.inJustDecodeBounds = false; 
    bm = BitmapFactory.decodeFile(selectedImagePath, options); 

    imgPic.setImageBitmap(bm); 

} 
+0

'System.err:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法java.lang.String java.io.File.getAbsolutePath()' –

+0

发生了哪个错误? –

+0

我编辑了答案,请立即尝试 –

2

这是我为你制作的代码,它首先在你的清单中添加权限,并且已经完全测试过了。您minifest文件应该是这个样子

<?xml version="1.0" encoding="utf-8"?> 

<uses-permission android:name="android.permission.CAMERA"></uses-permission> 
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission> 
<application 
    android:allowBackup="true" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    android:supportsRtl="true" 
    android:theme="@style/AppTheme"> 




    <activity 
     android:name=".MainActivity" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme.NoActionBar"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
    <!-- ATTENTION: This was auto-generated to add Google Play services to your project for 
     App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information. --> 
    <meta-data 
     android:name="com.google.android.gms.version" 
     android:value="@integer/google_play_services_version" /> 
</application> 

</manifest> 

那么你的XML布局文件应该是这样的

<?xml version="1.0" encoding="utf-8"?> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Hello World!" 
    android:id="@+id/textView" /> 

<ImageView 
    android:layout_width="200dp" 
    android:layout_height="200dp" 
    android:id="@+id/imageView" 
    android:layout_below="@+id/textView" 
    android:layout_toRightOf="@+id/textView" 
    android:layout_toEndOf="@+id/textView" 
    android:layout_marginTop="161dp" /> 
</RelativeLayout> 

,这里是你的活动级别

public class MainActivity extends AppCompatActivity { 

private static final int REQUEST_CAMERA = 101; 
private static final int SELECT_FILE = 102; 
/** 
* ATTENTION: This was auto-generated to implement the App Indexing API. 
* See https://g.co/AppIndexing/AndroidStudio for more information. 
*/ 
private GoogleApiClient client; 

private ImageView ivImage; @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ivImage =(ImageView)findViewById(R.id.imageView); 工具栏工具栏=(工具栏)findViewById(R.id.toolbar); setSupportActionBar(toolbar);

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
    fab.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) 
        .setAction("Action", null).show(); 
      selectImage(); 
     } 
    }); 
    // ATTENTION: This was auto-generated to implement the App Indexing API. 
    // See https://g.co/AppIndexing/AndroidStudio for more information. 
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); 
} 




@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_main, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    //noinspection SimplifiableIfStatement 
    if (id == R.id.action_settings) { 
     return true; 
    } 

    return super.onOptionsItemSelected(item); 
} 


private void selectImage() { 
    final CharSequence[] items = {"Take Photo", "Choose from Library", 
      "Cancel"}; 

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); 
    builder.setTitle("Add Photo!"); 
    builder.setItems(items, new DialogInterface.OnClickListener() { 
     @Override 
     public void onClick(DialogInterface dialog, int item) { 
      if (items[item].equals("Take Photo")) { 
       Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
       File f = new File(Environment 
         .getExternalStorageDirectory(), "temp.jpg"); 
       intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f)); 
       startActivityForResult(intent, REQUEST_CAMERA); 
      } else if (items[item].equals("Choose from Library")) { 
       Intent intent = new Intent(
         Intent.ACTION_PICK, 
         MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
       intent.setType("image/*"); 
       startActivityForResult(
         Intent.createChooser(intent, "Select File"), 
         SELECT_FILE); 
      } else if (items[item].equals("Cancel")) { 
       dialog.dismiss(); 
      } 
     } 
    }); 
    builder.show(); 
} 


@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    if (resultCode == RESULT_OK) { 
     if (requestCode == REQUEST_CAMERA) { 
      File f = new File(Environment.getExternalStorageDirectory() 
        .toString()); 
      for (File temp : f.listFiles()) { 
       if (temp.getName().equals("temp.jpg")) { 
        f = temp; 
        break; 
       } 
      } 
      try { 
       Bitmap bm; 
       BitmapFactory.Options btmapOptions = new BitmapFactory.Options(); 

       bm = BitmapFactory.decodeFile(f.getAbsolutePath(), 
         btmapOptions); 

       // bm = Bitmap.createScaledBitmap(bm, 70, 70, true); 
       ivImage.setImageBitmap(bm); 

       String path = Environment 
         .getExternalStorageDirectory() 
         + File.separator 
         + "Phoenix" + File.separator + "default"; 
       f.delete(); 
       OutputStream fOut = null; 
       File file = new File(path, String.valueOf(System 
         .currentTimeMillis()) + ".jpg"); 
       try { 
        fOut = new FileOutputStream(file); 
        bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut); 
        fOut.flush(); 
        fOut.close(); 
       } catch (FileNotFoundException e) { 
        e.printStackTrace(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } else if (requestCode == SELECT_FILE) { 
      Uri selectedImageUri = data.getData(); 

      String tempPath = getPath(selectedImageUri, MainActivity.this); 
      Bitmap bm; 
      BitmapFactory.Options btmapOptions = new BitmapFactory.Options(); 
      bm = BitmapFactory.decodeFile(tempPath, btmapOptions); 
      ivImage.setImageBitmap(bm); 
     } 
    } 
} 

public String getPath(Uri uri, Activity activity) { 
    String[] projection = {MediaStore.MediaColumns.DATA}; 
    Cursor cursor = activity 
      .managedQuery(uri, projection, null, null, null); 
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA); 
    cursor.moveToFirst(); 
    return cursor.getString(column_index); 
} 

@Override 
public void onStart() { 
    super.onStart(); 

    // ATTENTION: This was auto-generated to implement the App Indexing API. 
    // See https://g.co/AppIndexing/AndroidStudio for more information. 
    client.connect(); 
    Action viewAction = Action.newAction(
      Action.TYPE_VIEW, // TODO: choose an action type. 
      "Main Page", // TODO: Define a title for the content shown. 
      // TODO: If you have web page content that matches this app activity's content, 
      // make sure this auto-generated web page URL is correct. 
      // Otherwise, set the URL to null. 
      Uri.parse("http://host/path"), 
      // TODO: Make sure this auto-generated app deep link URI is correct. 
      Uri.parse("android-app://com.group3amd.myapplication/http/host/path") 
    ); 
    AppIndex.AppIndexApi.start(client, viewAction); 
} 

@Override 
public void onStop() { 
    super.onStop(); 

    // ATTENTION: This was auto-generated to implement the App Indexing API. 
    // See https://g.co/AppIndexing/AndroidStudio for more information. 
    Action viewAction = Action.newAction(
      Action.TYPE_VIEW, // TODO: choose an action type. 
      "Main Page", // TODO: Define a title for the content shown. 
      // TODO: If you have web page content that matches this app activity's content, 
      // make sure this auto-generated web page URL is correct. 
      // Otherwise, set the URL to null. 
      Uri.parse("http://host/path"), 
      // TODO: Make sure this auto-generated app deep link URI is correct. 
      Uri.parse("android-app://com.group3amd.myapplication/http/host/path") 
    ); 
    AppIndex.AppIndexApi.end(client, viewAction); 
    client.disconnect(); 
} 
} 
+0

它工作....谢谢 –

+0

请接受,如果它是有用的:) –

2

这里是下面的代码可以解决你的问题

MainActivity。java的

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

import android.app.Activity; 
import android.app.AlertDialog; 
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.MediaColumns; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.ImageView; 

import com.example.takeimage.R; 

public class MainActivity extends Activity { 

    int REQUEST_CAMERA = 0, SELECT_FILE = 1; 
    Button btnSelect; 
    ImageView ivImage; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     btnSelect = (Button) findViewById(R.id.btnSelectPhoto); 
     btnSelect.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       selectImage(); 
      } 
     }); 
     ivImage = (ImageView) findViewById(R.id.ivImage); 
    } 

    private void selectImage() { 
     final CharSequence[] items = { "Take Photo", "Choose from Library", 
       "Cancel" }; 

     AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); 
     builder.setTitle("Add Photo!"); 
     builder.setItems(items, new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialog, int item) { 
       if (items[item].equals("Take Photo")) { 
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
        startActivityForResult(intent, REQUEST_CAMERA); 
       } else if (items[item].equals("Choose from Library")) { 
        Intent intent = new Intent(
          Intent.ACTION_PICK, 
          android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
        intent.setType("image/*"); 
        startActivityForResult(
          Intent.createChooser(intent, "Select File"), 
          SELECT_FILE); 
       } else if (items[item].equals("Cancel")) { 
        dialog.dismiss(); 
       } 
      } 
     }); 
     builder.show(); 
    } 

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

     if (resultCode == Activity.RESULT_OK) { 
      if (requestCode == SELECT_FILE) 
       onSelectFromGalleryResult(data); 
      else if (requestCode == REQUEST_CAMERA) 
       onCaptureImageResult(data); 
     } 
    } 

    private void onCaptureImageResult(Intent data) { 
     Bitmap thumbnail = (Bitmap) data.getExtras().get("data"); 
     ByteArrayOutputStream bytes = new ByteArrayOutputStream(); 
     thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes); 

     File destination = new File(Environment.getExternalStorageDirectory(), 
       System.currentTimeMillis() + ".jpg"); 

     FileOutputStream fo; 
     try { 
      destination.createNewFile(); 
      fo = new FileOutputStream(destination); 
      fo.write(bytes.toByteArray()); 
      fo.close(); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     ivImage.setImageBitmap(thumbnail); 
    } 

    @SuppressWarnings("deprecation") 
    private void onSelectFromGalleryResult(Intent data) { 
     Uri selectedImageUri = data.getData(); 
     String[] projection = { MediaColumns.DATA }; 
     Cursor cursor = managedQuery(selectedImageUri, projection, null, null, 
       null); 
     int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA); 
     cursor.moveToFirst(); 

     String selectedImagePath = cursor.getString(column_index); 

     Bitmap bm; 
     BitmapFactory.Options options = new BitmapFactory.Options(); 
     options.inJustDecodeBounds = true; 
     BitmapFactory.decodeFile(selectedImagePath, options); 
     final int REQUIRED_SIZE = 200; 
     int scale = 1; 
     while (options.outWidth/scale/2 >= REQUIRED_SIZE 
       && options.outHeight/scale/2 >= REQUIRED_SIZE) 
      scale *= 2; 
     options.inSampleSize = scale; 
     options.inJustDecodeBounds = false; 
     bm = BitmapFactory.decodeFile(selectedImagePath, options); 

     ivImage.setImageBitmap(bm); 
    } 

} 

activity_main

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/LinearLayout1" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    android:padding="10dp" > 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:gravity="center" 
     android:padding="5dp" > 

     <Button 
      android:id="@+id/btnSelectPhoto" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:text="Select Photo" /> 
    </LinearLayout> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:gravity="center" 
     android:orientation="vertical" 
     android:padding="10dp" > 

     <ImageView 
      android:id="@+id/ivImage" 
      android:layout_width="200dp" 
      android:layout_height="200dp" 
      android:scaleType="fitXY" 
      android:adjustViewBounds="true" 
      android:src="@drawable/ic_launcher" /> 
    </LinearLayout> 

</LinearLayout> 

后,在清单文件放在以下权限: -

AndroidManifest.xml中

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.takeimage" 
    android:versionCode="1" 
    android:versionName="1.0" > 

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

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme" > 
     <activity 
      android:name="com.tag.photocaptureandgallery.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> 
    </application> 

</manifest>