从图库中选择图像并在imageview中显示

时间:2015-03-05 05:53:56

标签: android image gallery

这个我的代码不工作如何从图库中拾取图像并在imageview中显示

public class MainActivity extends ActionBarActivity {
    Button imageUpload;
    ImageView imageView;
    static final int PICTURE = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView= (ImageView) findViewById(R.id.imageView);
        imageUpload= (Button) findViewById(R.id.buttonImage);
        imageUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent,PICTURE);

            }
        });
    }

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

        switch (requestCode)
        {
            case PICTURE:
                if(requestCode==RESULT_OK){

                    Uri uri = data.getData();
                    String[] prjection ={MediaStore.Images.Media.DATA};
                    Cursor cursor=getContentResolver().query(uri,prjection,null,null,null);
                    cursor.moveToFirst();

                    int columnIndex=cursor.getColumnIndex(prjection[0]);
                    String path=cursor.getString(columnIndex);
                    cursor.close();

                    Bitmap selectFile = BitmapFactory.decodeFile(path);
                    Drawable d = new BitmapDrawable(selectFile);
                    imageView.setBackground(d);
                }
        }

    }

你好朋友我是android的新手我需要这种类型的应用程序上传图片并在imageview中显示plz帮助我如果有idea.thanks提前

4 个答案:

答案 0 :(得分:1)

Finnay此代码正常工作,我们可以提供在特定区域显示的固定大小的imageview layout.xml

 <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Image Upload"
        android:id="@+id/buttonImage"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <ImageView

        android:layout_width="100dp"
        android:layout_height="100dp"
        android:id="@+id/imageView"
        android:layout_x="13dp"
        android:layout_y="112dp" />
Main Activity



      Button imageUpload;
        ImageView imageView;
        static final int PICTURE = 1;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            imageView= (ImageView) findViewById(R.id.imageView);
            imageUpload= (Button) findViewById(R.id.buttonImage);
            imageUpload.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent,PICTURE);

                }
            });
        }

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

            if (requestCode==PICTURE && resultCode==RESULT_OK && null !=data)
            {

                Uri uri = data.getData();
                String[] prjection ={MediaStore.Images.Media.DATA};
                Cursor cursor=getContentResolver().query(uri,prjection,null,null,null);
                cursor.moveToFirst();

                int columnIndex=cursor.getColumnIndex(prjection[0]);
                String path=cursor.getString(columnIndex);
                cursor.close();

                Bitmap selectFile = BitmapFactory.decodeFile(path);


                Drawable d = new BitmapDrawable(selectFile);
                imageView.setBackground(d);


               // imageView.setImageBitmap(BitmapFactory.decodeFile(path));
            }


        }

最后这段代码正在运作

答案 1 :(得分:0)

替换

Bitmap selectFile = BitmapFactory.decodeFile(path);
                    Drawable d = new BitmapDrawable(selectFile);
                    imageView.setBackground(d);

imageView = (ImageView) findViewById(R.id.imageView);
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath)); 

答案 2 :(得分:0)

使用此代码

    uploadPic.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            selectImage();
        }
    });



private void selectImage() {

    final CharSequence[] options = {  "Take Photo", "Choose from Gallery", "Cancel" };

    AlertDialog.Builder builder = new AlertDialog.Builder(yourActivity.this);
    builder.setTitle("Add Photo!");
    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("Choose from Gallery")) {
                Intent intent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 2);

            } else if (options[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 == 1) {
            File f = new File(Environment.getExternalStorageDirectory().toString());
            for (File temp : f.listFiles()) {
                if (temp.getName().equals("temp.jpg")) {
                    f = temp;
                    break;
                }
            }
            try {

                BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();

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

                pic.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) {

            Uri selectedImage = data.getData();
            String[] filePath = { MediaStore.Images.Media.DATA };
            Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePath[0]);
            picturePath = c.getString(columnIndex);
            c.close();

             bitmap = (BitmapFactory.decodeFile(picturePath)); Log.w(
              "path of image from gallery......******************........."
              , picturePath+""); pic.setImageBitmap(bitmap);

            decodeFile(picturePath);

        }
    }
}

public void decodeFile(String filePath) {
    // Decode image size
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, o);

    // The new size we want to scale to
    final int REQUIRED_SIZE = 300;

    // Find the correct scale value. It should be the power of 2.
    int width_tmp = o.outWidth, height_tmp = o.outHeight;
    int scale = 1;
    while (true) {
        if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
            break;
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
    }

    // Decode with inSampleSize
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    bitmap = BitmapFactory.decodeFile(filePath, o2);

    pic.setImageBitmap(bitmap);
}

获取更多帮助...转到此link

答案 3 :(得分:0)

此外,在onActivityResult中,switchif语句都在检查requestCode。因此,if永远不会成立。

替换

if(requestCode==RESULT_OK)

if(resultCode==RESULT_OK)