Getting Black Screen when displaying Gallery picture into ImageView Android - android

#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_read_palm:
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
break;
case R.id.btn_read_from_existing:
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMG);
break;
}
}
Here getting selectedImageUri = content://media/external/images/media/2997
and
path = /storage/emulated/0/DCIM/Camera/IMG_20170510_132342860.jpg
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case CAMERA_REQUEST:
Bitmap photo = (Bitmap) data.getExtras().get("data");
saveAndShowPictureDialog(photo);
break;
case RESULT_LOAD_IMG:
Uri selectedImageUri = data.getData();
String path = getRealPathFromURI(this, selectedImageUri);
if (path != null)
showImageDialog(path);
}
}
}
getRealPathFromURI function returning correct path.
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
assert cursor != null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
private void showImageDialog(String pictureFile) {
// custom dialog
final Dialog dialog = new Dialog(this, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
dialog.setContentView(R.layout.image_dialog);
dialog.setTitle("Image");
// find the imageview and draw it!
ImageView image = (ImageView) dialog.findViewById(R.id.image);
Bitmap bmImg = BitmapFactory.decodeFile(pictureFile);
here i am getting a black screen/image on imageview when setting Image Bitmap from the picture file.
image.setImageBitmap(bmImg);
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}

Try the following instead of Bitmap bmImg = BitmapFactory.decodeFile(pictureFile);?
Bitmap bmImg;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
bmImg = BitmapFactory.decodeFile(selectedImagePath, options);
image.setImageBitmap(bmImg);

ImageView's have a display resolution limit based on OpenGL. Normally this limit is about 2048 x 2048. If you go above that limit, the ImageView will just show black and throw no error.
This is particularly irritating with gallery images / camera images, since those can be very high resolution.
It's also irritating because the OpenGL limit can vary heavily based on the device. Therefore, the error is very hard to reproduce.
You can query the exact maximum resolution with something like this:
int[] maxSize = new int[1];
GLES10.glGetIntegerv(GL10.GL_MAX_TEXTURE_SIZE, maxSize, 0);
This answer goes into a little more detail about OpenGL and these limitations with regard to maximum width and height of a bitmap

Related

Android - Dialog not refresing ImageView when getting image from gallery/ camera

So i´m working on an app in which I need to show a dialog, and inside this dialog, the user can press a button to select an image from the gallery or take a photo from the camera and display that image on an ImageView inside a dialog´s ImageView.
I´m able to take the photo from the camera/gallery, and then i use it as the ImageView image, but it doesn´t show it until i press the button again, as if the layout had to be refreshed.
This is my code:
To call the dialog (get_permissions(); is used on Android M for getting the write and read storage permissions, this works correctly)
protected void createDialog() {
final Dialog dialog = new Dialog(WeightActivity.this, android.R.style.Theme_Material_Light_Dialog_Alert);
dialog.getWindow();
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_add_weight);
Button okButton = (Button) dialog.findViewById(R.id.okButton);
final ImageButton selectImageButton = (ImageButton) dialog.findViewById(R.id.selectImageButton);
final ImageView imageView = (ImageView) dialog.findViewById(R.id.imageView);
selectImageButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
get_permissions();
selectImage();
imageView.setImageBitmap(bm);
}
});
dialog.show();
}
private void selectImage() {
final String[] items = WeightActivity.this.getResources().getStringArray(R.array.photo_options);
AlertDialog.Builder builder = new AlertDialog.Builder(WeightActivity.this);
builder.setTitle(R.string.weight_dialog_add_photo);
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals(items[0])) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals(items[1])) {
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);
}
}
});
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) {
bm = (Bitmap) data.getExtras().get("data");
} else if (requestCode == SELECT_FILE) {
Uri selectedImageUri = data.getData();
String[] projection = {MediaStore.MediaColumns.DATA};
CursorLoader cursorLoader = new CursorLoader(this, selectedImageUri, projection, null, null,
null);
Cursor cursor = cursorLoader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImagePath, options);
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(selectedImagePath, options);
}
}
}
Could somebody help me please??
Thanks a lot!
The problem is this,
get_permissions();
selectImage();
imageView.setImageBitmap(bm);
selectImage() starts the activity, but it doesn't block; it returns immediately. You then call setImageBitmap(), probably on a null valued bm instance field.
Move, or otherwise trigger the imageView.setImageBitmap() call in onActivityResult(), only after you have decoded the image.

Android Camera Intent crashes with Android L

My app is working properly on all api till Kitkat but it's not working in lollipop. The moment i clicks for capturing a photo using camera in my app, it crashes.
cam.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
This is my onActivityResult()
case CAMERA_REQUEST: {
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();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(picturePath, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;
options.inSampleSize = calculateInSampleSize(options,200,100);//512 and 256 whatever you want as scale
options.inJustDecodeBounds = false;
Bitmap yourSelectedImage = BitmapFactory.decodeFile(picturePath,options);
File pngDir = new File(Environment.getExternalStorageDirectory(),"PicUploadTemp");
if (!pngDir.exists()) {
pngDir.mkdirs();
}
File pngfile = new File(pngDir,"texture1.jpg");
FileOutputStream fOut;
try {
fOut = new FileOutputStream(pngfile);
yourSelectedImage.compress(Bitmap.CompressFormat.JPEG, 50,fOut);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Drawable d = Drawable.createFromPath(pngfile.getPath().toString());
rlLayout.setBackground(d);
yourSelectedImage.recycle();
// resizedBitmap.recycle();
xfile = pngfile;
}
break;
I want to compress the image and this above code is working amazingly for gingerbread, ICS , kitkat but not for Android L
I am getting null pointer Exception
Please suggest me some solution
Thanks in advance
Cannot really say anything about this without the logcat output, It may be becoming null in as a result of you using on of the deprecated method in the BitmapFacotry class.
Define these globally in your activity,
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
private static final int CAMERA_REQUEST = 1888;
in button click call your camera intent like this
startActivityForResult(cameraIntent, CAMERA_REQUEST);
make sure to use
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
use this to retrieve photo
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == getActivity().RESULT_OK) {
//get photo
Bitmap photo = (Bitmap) data.getExtras().get("data");
}

Android - ImageView won't show pic taken with camera

Please bear with me... I've been looking around for DAYS for a working, bare-bones piece of code that starts the camera activity, takes a picture, and places it on a simple ImageView >.< The code posted below fires up the activity and takes the pic alright, but the image does not show on the ImageView! Just what is missing? :'(
public class MainActivity extends Activity
{
private static final int PICK_IMAGE = 0;
private static final int PICK_IMAGE_FROM_GALLERY = 1;
private Button mBtnCamera, mBtnGallery, mBtnCancel;
private ImageView mImageView;
private Uri mURI;
private String mPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = (ImageView) findViewById(R.id.imgDisplayImage);
mBtnCamera = (Button) findViewById(R.id.btnPhotoCamera);
mBtnGallery = (Button) findViewById(R.id.btnPhotoGallery);
mBtnCancel = (Button) findViewById(R.id.btnCancel);
mBtnCamera.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent camera = new Intent();
camera.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
camera.putExtra("crop", "true");
File f = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
mURI = Uri.fromFile(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "myFile.jpg"));
camera.putExtra(MediaStore.EXTRA_OUTPUT, mURI);
startActivityForResult(camera, PICK_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == PICK_IMAGE)
{
// Result includes a Bitmap thumbnail?
if (data != null)
{
if (data.hasExtra("data"))
{
//Bitmap thumbnail = data.getParcelableExtra("data");
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
mImageView.setImageBitmap(thumbnail);
}
}
// If there is no thumbnail data, the image will have been stored in target output URI.
else
{
Cursor cursor = getContentResolver().query(
Media.EXTERNAL_CONTENT_URI, new String[]
{
Media.DATA,
Media.DATE_ADDED,
MediaStore.Images.ImageColumns.ORIENTATION
},
Media.DATE_ADDED,
null,
"date_added ASC"
);
if (cursor != null && cursor.moveToFirst())
{
do
{
mURI = Uri.parse(cursor.getString(cursor.getColumnIndex(Media.DATA)));
mPhotoPath = mURI.toString();
}
while (cursor.moveToNext());
cursor.close();
}
// Resize full image to fit out in image view.
int width = mImageView.getWidth();
int height = mImageView.getHeight();
BitmapFactory.Options factoryOptions = new BitmapFactory.Options();
factoryOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(/*mURI.getPath()*/ mPhotoPath, factoryOptions);
int imageWidth = factoryOptions.outWidth;
int imageHeight = factoryOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(
imageWidth/width,
imageHeight/height
);
// Decode the image file into a Bitmap sized to fill view
factoryOptions.inJustDecodeBounds = false;
factoryOptions.inSampleSize = scaleFactor;
factoryOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(/*mURI.getPath()*/ mPhotoPath, factoryOptions);
mImageView.setImageBitmap(bitmap);
}
}
}
}
I had same problem in some devices of samsung android Then I implemented logic to get path of captured photo.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == PICK_IMAGE)
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
Cursor cursor = getContentResolver().query(Media.EXTERNAL_CONTENT_URI, new String[]{Media.DATA, Media.DATE_ADDED, MediaStore.Images.ImageColumns.ORIENTATION}, Media.DATE_ADDED, null, "date_added ASC");
if(cursor != null && cursor.moveToFirst())
{
do {
uri = Uri.parse(cursor.getString(cursor.getColumnIndex(Media.DATA)));
photoPath = uri.toString();
}while(cursor.moveToNext());
cursor.close();
}
if(photoPath != null) {
Bitmap bitmap = BitmapFactory.decodeFile(photoPath);
///Do Implement your logic whatever you want.
mImageView.setImageBitmap(bitmap);
}
}
}
Tried and tested to work on a Galaxy S3 phone. Credit to TGMCians for his help.
public class MainActivity extends Activity
{
private static final int PICK_IMAGE = 0;
private static final int PICK_IMAGE_FROM_GALLERY = 1;
private Button mBtnCamera, mBtnGallery, mBtnCancel;
private ImageView mImageView;
private Uri mURI;
private String mPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = (ImageView) findViewById(R.id.imgDisplayImage);
mBtnCamera = (Button) findViewById(R.id.btnPhotoCamera);
mBtnGallery = (Button) findViewById(R.id.btnPhotoGallery);
mBtnCancel = (Button) findViewById(R.id.btnCancel);
mBtnCamera.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent camera = new Intent();
camera.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
camera.putExtra("crop", "true");
File f = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
mURI = Uri.fromFile(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "myFile.jpg"));
camera.putExtra(MediaStore.EXTRA_OUTPUT, mURI);
startActivityForResult(camera, PICK_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == Activity.RESULT_OK)
{
if (requestCode == PICK_IMAGE)
{
Cursor cursor = getContentResolver().query(
Media.EXTERNAL_CONTENT_URI, new String[]
{
Media.DATA,
Media.DATE_ADDED,
MediaStore.Images.ImageColumns.ORIENTATION
},
Media.DATE_ADDED,
null,
"date_added ASC"
);
if (cursor != null && cursor.moveToFirst())
{
do
{
mURI = Uri.parse(cursor.getString(cursor.getColumnIndex(Media.DATA)));
mPhotoPath = mURI.toString();
}
while (cursor.moveToNext());
cursor.close();
}
if (data != null)
{
if (data.hasExtra("data"))
{
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
mImageView.setImageBitmap(thumbnail);
}
else
{
System.out.println("Intent bundle does not have the 'data' Extra");
int width = mImageView.getWidth();
int height = mImageView.getHeight();
BitmapFactory.Options factoryOptions = new BitmapFactory.Options();
factoryOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(/*mURI.getPath()*/ mPhotoPath, factoryOptions);
int imageWidth = factoryOptions.outWidth;
int imageHeight = factoryOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(
imageWidth/width,
imageHeight/height
);
// Decode the image file into a Bitmap sized to fill view
factoryOptions.inJustDecodeBounds = false;
factoryOptions.inSampleSize = scaleFactor;
factoryOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(/*mURI.getPath()*/ mPhotoPath, factoryOptions);
mImageView.setImageBitmap(bitmap);
}
}
}
}
else
{
System.out.println("Picture taking activity NOT returning RESULT_OK");
}
}
}
Try adding
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
(and a slight delay) right inside the
if (requestCode == PICK_IMAGE)
block. I think the problem might be that your device isn't refreshing the Media store correctly.
(of course the better action would be to use MediaScanner to scan your file)

Pick Gallery Image In Android Causing Issue

I am using a very simple code to pick image from gallery, it work on my phone.
but testing it on three to four phones(Galaxy S3,Tablet etc..) it does not work.
Environment It Works:
if the image size i took or was in gallery below 500kb then it works
Environment It Does'nt Work:
if the image size i took or was in gallery above 500kb then it works
ImageView myimg;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Toast.makeText(this, UUID.randomUUID().toString(),
// Toast.LENGTH_LONG).show();
myimg = (ImageView) findViewById(R.id.imageView1);
mybutton = (Button) findViewById(R.id.myButton);
mybutton.setOnClickListener(this);
}
public void onClick(View v) {
if (v == mybutton) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.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 filePath = cursor.getString(columnIndex); // file path of
// selected
// image
cursor.close();
// Convert file path into bitmap image using below line.
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
// put bitmapimage in your imageview
myimg.setImageBitmap(yourSelectedImage);
}
}
}
Any one put some light on it how to handle this situation?
Any help would be appreciated.

How to increase Bitmap quality?

In the app I'm working on, a button opens the camera. When you take a picture, that picture is loaded into the app as a Bitmap. The pictures are very pixelated. How can I increase the quality of the bitmap after it has been loaded into my app?
Code so far:
private static final int CAMERA_PIC_REQUEST = 2500;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button capture = (Button) findViewById(R.id.captureButton);
Button flip = (Button) findViewById(R.id.flipButton);
final TextView text = (TextView) findViewById(R.id.text);
capture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
text.setVisibility(View.GONE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
});
flip.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == CAMERA_PIC_REQUEST){
Bitmap image = (Bitmap) data.getExtras().get("data");
ImageView imageView = (ImageView) findViewById(R.id.ImageView01);
imageView.setImageBitmap(image);
}
}
}
Do not get that image from data, it is always a low quality image. Try using a file path and get the image from file path.
Open Camera
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(path));
startActivityForResult(intent, CAMERA_PIC_REQUEST);
And when you return to onActivityResult the image will be stored to your defined path. You can get the high resolution image from there. Or you can also use a function to get last captured image ...
private String getLastImagePath() {
final String[] imageColumns = { MediaStore.Images.Media._ID,
MediaStore.Images.Media.DATA };
final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
Cursor imageCursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns,
null, null, imageOrderBy);
if (imageCursor.moveToFirst()) {
int id = imageCursor.getInt(imageCursor
.getColumnIndex(MediaStore.Images.Media._ID));
String fullPath = imageCursor.getString(imageCursor
.getColumnIndex(MediaStore.Images.Media.DATA));
return fullPath;
} else {
return "";
}
}
This function will return you the last captured image path.

Categories

Resources