imageview不显示所选图像

时间:2016-10-06 06:35:32

标签: java android sdk

我正在制作一个活动,其中有一个按钮,当用户点击弹出窗口时,会出现从图库中选择图像并在按钮上方显示之后显示的图像。我想出了一种从图库中获取图像的方法,但它并没有显示在图像视图中。另外,如果我按下跳过,我无法找到设置默认图片的方法。什么是将所选图像存储在数据库中的好选择?

imagePicker.java

 public class imagePicker extends AppCompatActivity {

private static int RESULT_LOAD_IMAGE = 1;

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

    Typeface tf = Typeface.createFromAsset(getAssets(),
            "fonts/Psilly.otf");
    TextView tv = (TextView) findViewById(R.id.select);
    tv.setTypeface(tf);
    tv.setText("Set Your Profile Picture");

}

public void choose(View view) {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent,
            "Select Picture"), RESULT_LOAD_IMAGE);
}

public void chats(View view) {
    Intent i = new Intent(this, Chats.class);
    startActivity(i);
}


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

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

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

    }

}
}

xml文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.nagpal.karan.radarchat.imagePicker"
android:background="@color/white">

<ImageView
    android:layout_width="250dp"
    android:layout_height="200dp"
    android:background="@drawable/pic_stroke"
    android:id="@+id/galpic"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="130dp" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Choose from gallery"
    android:id="@+id/gallery"
    android:background="@drawable/button_shape"
    android:textSize="18dp"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="140dp"
    android:onClick="choose"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Skip >"
    android:id="@+id/skip"
    android:textSize="18dp"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:background="@drawable/button_shape"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="70dp"
    android:onClick="chats"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Set Your Profile Picture"
    android:id="@+id/select"
    android:textSize="25dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="50dp" />
</RelativeLayout>

pic_stroke.xml:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@android:color/white" />
<stroke android:width="3dp" android:color="@android:color/black" />
</shape>

3 个答案:

答案 0 :(得分:0)

您是否已将以下内容添加到AndroidManifest.xml

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

答案 1 :(得分:0)

将您的选择方法更改为: -

public void choose(View view) 
{

Intent intent = new Intent(Intent.ACTION_PICK,  MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), RESULT_LOAD_IMAGE);

}

并添加清单

的权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

对于默认图像将其放在资源可绘制中并从那里加载它。您应该将图像保存在缓存中。 android中有varoius缓存选项。

答案 2 :(得分:0)

    private void showDialog()
{
    try {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("Please select Profile picture");
        builder.setPositiveButton("Gallery", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                pickProfilePicFromGallary();
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("Camera", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                pickProfilePicFromCamera();
                dialog.dismiss();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

 private void pickProfilePicFromGallary() {
    try {
        Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, GALLARY);
    } catch (Exception e) {
        e.printStackTrace();
    }
}


private void pickProfilePicFromCamera() {
    try {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp1.jpg");
        mImageCaptureUri = Uri.fromFile(f);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
        startActivityForResult(intent, CAMERA);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

    @Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
    try {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GALLARY && resultCode == getActivity().RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            performCrop(selectedImage);
        } else if (requestCode == CAMERA && resultCode == getActivity().RESULT_OK) {
            CropingIMG();
        } else if (requestCode == CAMERA_CROP) {
            try {
                if (outPutFile.exists()) {
                    Bitmap photo = decodeFile(outPutFile);

                    ivProfile.setImageBitmap(photo);


                    filepathForLOGO = getRealPathFromURI(Uri.fromFile(outPutFile));

                    try {
                        base64LOGO = GlobalMethod
                                .getBase64FromByteArray(GlobalMethod
                                        .convertFileToByteArray(new File(
                                                filepathForLOGO)));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                } else {

                    AlertDialogUtility.showToast(getActivity(), "Error while save image");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestCode == GALLARY_CROP) {
            File imageFile = new File(makeDir(), "ABC.png");
            if (imageFile.exists()) {
                String imagePath = imageFile.getAbsolutePath();
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                Bitmap thePic = BitmapFactory.decodeFile(imagePath, options);
                options.inSampleSize = 2;
                options.inJustDecodeBounds = false;
                thePic = BitmapFactory.decodeFile(imagePath, options);
                ivProfile.setImageBitmap(thePic);
                filepathForLOGO = getRealPathFromURI(getImageUri(getActivity(), thePic));

                try {
                    base64LOGO = GlobalMethod
                            .getBase64FromByteArray(GlobalMethod
                                    .convertFileToByteArray(new File(
                                            filepathForLOGO)));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

  public Uri getImageUri(Context inContext, Bitmap inImage)
{
    try {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
        return Uri.parse(path);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null ;
}


private Bitmap decodeFile(File f) {
    try {
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(new FileInputStream(f), null, o);

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

        // decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
    } catch (FileNotFoundException e) {
    }
    return null;
}

    public static String getBase64FromByteArray(byte[] byteArray) {
    String base64 = "";
    try {
        System.gc();
        base64 = com.shantiniketan.Utils.Base64
                .encodeBytes(byteArray);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return base64;
}

    public static  byte[] convertFileToByteArray(File file) throws Exception {
    ByteArrayOutputStream baos = null;
    try {
        FileInputStream fis = new FileInputStream(file);
        baos = new ByteArrayOutputStream();
        System.gc();
        // Log.d("TAG", "::::: " + file.length());
        int fileSize = (int) file.length();
        byte[] buff = new byte[fileSize];
        int i = Integer.MAX_VALUE;
        while ((i = fis.read(buff, 0, buff.length)) > 0) {
            baos.write(buff, 0, i);
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return baos.toByteArray(); // be sure to close InputStream in calling
    // function
}