I want to let a image on my phone to show up in the Imageview. But in the ANdroid Studio emulator it is working but not on my own phone.
String imgPath = getIntent().getExtras().getString("imgPath");
System.out.println(imgPath);
if(!imgPath.equals("?"))
{
File img_file = new File(imgPath);
ImageView imgView = findViewById(R.id.show_image_war);
imgView.setImageURI(Uri.fromFile(img_file));
}
The path is /storage/emulated/0/imagesWarranty/img_MyWarranty_ID1.jpg . Both on the image in my phone and the path in my code where I get the image.
It might be issue of resolution. Even I was getting error of resolution while I was displaying image from uri.
I used below code and It worked for me :
Uri imageUri = Uri.parse(imagePath);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(new File(imageUri.getPath()).getAbsolutePath(), options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
if (imageHeight > 4096 || imageWidth > 4096) {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(imageUri.toString(), opts);
viewHolder.imgAvatarLogoList3.setImageBitmap(bitmap);
} else {
Picasso.with(context)
.load(new File(imageUri.getPath())) // Uri of the picture
.into(viewHolder.imgAvatarLogoList3);
}
Addition to this answer [https://stackoverflow.com/a/48354307/9255006]
In that rotation bug define the image orientation for the image using ExifInterface.
Here is the code
private void SetOrientation(){
try {
ExifInterface exif=new ExifInterface(photoURI.getPath());
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_UNDEFINED);
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) { orientationInDegrees=90; }
else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) { orientationInDegrees=180; }
else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) { orientationInDegrees=270; }
else { orientationInDegrees=0; }
Toast.makeText(this, String.valueOf(orientationInDegrees), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
You can then set this orientation to your image.
This happens when the image has a very high resolution that the system needs some additional milliseconds to display, and since this happens in the UI thread onDraw() of the image view will draw it as an empty.
The easiest way I found for this issue is to use the Picasso library this way:
Picasso.get().load(imgUri).fit().centerCrop()
.into(imageview);
The reason behind those two methods (fit(), centerCrop())
Is that fit make sure that the image fit the bound container and then crop the image which force the system to redraw the image but this time with the convenient resolution (because of fit and crop).
Related
This question already has answers here:
Resize images with Glide in a ImageView Android
(6 answers)
Closed 4 years ago.
I want to resize image use by glide . Now I use a picasso but I want to use a glide
private void resizeImg(Context context, final File file, int targetSize, Handler handler) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file.getPath(), options);
float ratio = Math.max(options.outWidth, options.outHeight) / (float) targetSize;
//don't scale image that is smaller than targetSize
if (ratio < 1) return;
int dstWidth = (int) (options.outWidth / ratio);
int dstHeight = (int) (options.outHeight / ratio);
PicassoTargetFactory.getInstance().putTarget(file, handler);
Picasso.with(context)
.load(file)
.error(R.drawable.ic_delete)
.resize(dstWidth, dstHeight)
.into(PicassoTargetFactory.getInstance().getTarget(file));
ArrayList<String> paths = new ArrayList<>();
files = new ArrayList<>();
files.add(mCurrentPhotoPath);
for (File f : files) {
paths.add(f.getAbsolutePath());
}
mdb.insertPhotos(paths);
}
How I can do this ? On piccaso sometimes I have a cut image
first, add Glide lib in Gradle. Then, u can use it like this
Glide
.with(context)
.load("your image path")
.override(600, 200) // resizes the image to these dimensions (in pixel). resize does not respect aspect ratio
.into(imageViewResize);
Override must be accessed via RequestOptions in the most recent version of Glide.
Glide
.with(context)
.load(path)
.apply(new RequestOptions().override(600, 200))
.into(imageViewResizeCenterCrop);
You can create RequestOptions class object & pass it on apply() method in Glide.
Use like,
Glide.with(context)
.load(url)
.apply(new RequestOptions().override(Your image size here))
.into(imageView);
More From here
I think you should give your methods a single responsibility. You want a method that resizes an image but yours actually does more. Please separate things
private Bitmap resizeBitmap(Bitmap b, int w, int h) {
// Your code.
return myResizedBitmap;
}
Then it will be easier to help you
private String getImgCachePath(String url) {
FutureTarget<File> futureTarget = Glide.with(getBaseContext()).load(url).downloadOnly(100, 100);
try {
File file = futureTarget.get();
String path = file.getAbsolutePath();
return path;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return null;
}
100,100 is width and height of image you want to save, change it as per your need. path is the path of cached image of given resolution of image url.
I have an app which takes photos of receipts and upload it to a remote server.
I get the full-sized photo of the image from the camera intent correctly.I followed this using the official documentation in Google developer.
I then set my picture like this.
private void setPic() {
// Get the dimensions of the View
int targetW = imageView.getWidth();
int targetH = imageView.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
//Bitmap bitmap = null;
//try
//{
//bitmap = MediaStore.Images.Media.getBitmap(getContentResolver() , //Uri.parse(mCurrentPhotoPath));
//}
//catch (Exception e)
//{
//handle exception
//}
imageView.setImageBitmap(bitmap);
new ImageSaver(getApplicationContext()).
setFileName("currentImage.png").
setDirectoryName("Android_Upload").
save(bitmap);
Model.currentImage = "currentImage.png";
}
This works fine when viewed on the device. But after its sent to the server and viewed from there, the image size is too small.
ImageSaver class pretty much saves the image elsewhere and compresses it but with 100 quality in png.I do this, so I can later the image in the database as Blob(again with 100 quality)
How can I decode the image and show the image in the image view but without losing quality (and the size?)
Apparently, you have scaled down your image while decoding.
You may want to remove the following line:
bmOptions.inSampleSize = scaleFactor;
I am trying to simply get an image from a phone's camera. Surprisingly, it returns rotated. I've scoured the internet for fixes and came across many solutions using ExifInterface, but it only works sometimes. It gets the orientation wrong seemingly randomly, as I merely recompile and see different results. I have found some people saying this is a fault of the class itself being bugged.
I found other solutions that require like two additional libraries and more java files to do the job, but that just seems ridiculous (and I am avoiding additional packages). How come images are rotated in the first place (in storage they are perfectly fine), and how hard can it possibly be to fix the issue? Also - rotating the Image View also works (and seems much easier than literally creating a rotated image), but I need to know by how much to rotate the view.
EDIT---- I realized that the image is consistently rotated 270 degrees clockwise from the orientation the image was taken in (inside the intent) if the back camera was used, and 90 degrees if the front camera was used. Thus I only really need a way to find out this orientation.
Intent called here:
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = setUpPhotoFile();
mCurrentPhotoPath = photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
} catch (IOException ex) {
// Error occurred while creating the File
photoFile = null;
mCurrentPhotoPath = null;
}
// Continue only if the File was successfully created
if (photoFile != null) {
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
} else {
Toast noStorage = Toast.makeText(this, "Cannot access mounted storage.", Toast.LENGTH_SHORT);
noStorage.show();
}
}
}
Bitmap created here:
private void setPic() {
/* Get the size of the ImageView */
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
/* Get the size of the image */
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
/* Figure out which way needs to be reduced less */
int scale = 1;
if (photoH > targetH|| photoW > targetW) {
scale = Math.max(
(int)Math.pow(2, (int) Math.ceil(Math.log(targetW /
(double) photoW)) / Math.log(0.5)),
(int)Math.pow(2, (int) Math.ceil(Math.log(targetH /
(double) photoH)) / Math.log(0.5)));
;
}
/* Set bitmap options to scale the image decode target */
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scale;
/* Decode the JPEG file into a Bitmap */
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
/*-----------How should I rotate bitmap/mImageView to correct orientation?*/
/* Associate the Bitmap to the ImageView */
mImageView.setImageBitmap(bitmap);
mImageView.setVisibility(View.VISIBLE);
}
The best solution I have found is this one:
https://www.samieltamawy.com/how-to-fix-the-camera-intent-rotated-image-in-android/
I post the link because I don't want all the credit.
Sami Eltamawy has written a function that rotate the image if its need to be rotated.
I try the code and is working on my devices that the image got rotated.
This question already has answers here:
OutOfMemory exception when loading bitmap from external storage
(12 answers)
Closed 8 years ago.
My app uses images from the web to set wallpapers. However, when I try to use decodeStream using the BitmapFactory, some users on slower phones get an OutOfMemory exception. This image is never displayed on the app, it is just loaded, and then set as a wallpaper. I've searched online, but I've been unable to find any resources which help solve the problem.
Code:
public void setWallpaperMethod() {
InputStream in = null;
try {
in = new java.net.URL(urldisplay).openStream();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
final Bitmap bitmap = BitmapFactory.decodeStream(in);
myWallpaperManager = WallpaperManager
.getInstance(getApplicationContext());
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
myWallpaperManager.setBitmap(bitmap);
Toast.makeText(MainActivity.this,
"Teamwork! Wallpaper set.", Toast.LENGTH_LONG)
.show();
} catch (IOException e) {
Toast.makeText(
MainActivity.this,
"Damnit, clickers! Wallpaper wasn't set. Try killing and restarting the app?",
Toast.LENGTH_LONG).show();
}
}
});
}
The variable urldisplay is a string, equal to a URL (e.g., an imgur image). Also, the method is run in a thread, so there's no risk of the UI thread locking up.
So does anyone know how to solve this OutOfMemory Exception? All help appreciated.
Currently, you are opening an input stream, reading it, decoding a full fledge bitmap, then passing it to the manager, which will convert it to png and store it for later use.
Instead, you can open the input stream, pass it to the manager, which is now in charge of simply storing it for later use.
As you can see, that's one decoding and one encoding less.
Then, the wallpaper manager will be in charge of displaying the image, handling the image size accordingly.
myWallpaperManager = WallpaperManager
.getInstance(getApplicationContext());
myWallpaperManager.setStream(in);
voila !
(That is assuming the wallpaper manager properly handles oversized images, but that is very likely the case)
look at this link..
http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
Android Documentation suggest that you downsample the image.. using this method to calculate the sample size:
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
then you would do something like this:
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
I am having trouble of displaying the large image into android. I have tried to get this done by this custom- scrollable-image-view .
I have used full View in my class and used the 7165*786 size of image into it. And it is of only 1.11MB of image. I am able to run this code in bluestack and see the image in it but it couldn't be load in real device.
bmLargeImage = BitmapFactory.decodeResource(getResources(),
R.drawable.imagewithout);
bmlotusImage1 = BitmapFactory.decodeResource(getResources(),
R.drawable.lotus);
I am using the same canvas in onDraw methow as below.
canvas.drawBitmap(bmLargeImage, scrollRect, displayRect, paint);
canvas.drawBitmap(bmlotusImage1, 45 - newScrollRectX,
255 - newScrollRectY, paint);
i could not be able to display the bmlargeImage in my real device i can see the lotus image on Device but not the large one.
Should i have to decode or scale the image or anything else to get it display in real device?
i get the solution of not Displaying the image in real Device the problem was the simply.
I have just removed the target sdk a i get the error in webservice. It start showing the image to my real device also and also i get the solution for Displaying the image FIt to screen as below.
private static Bitmap ShrinkBitmap(String backgroundimage, int width,
int height) {
// TODO Auto-generated method stub
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(backgroundimage,
bmpFactoryOptions);
int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight
/ (float) height);
int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth
/ (float) width);
if (heightRatio > 1 || widthRatio > 1) {
if (heightRatio > widthRatio) {
bmpFactoryOptions.inSampleSize = heightRatio;
} else {
bmpFactoryOptions.inSampleSize = widthRatio;
}
}
bmpFactoryOptions.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFile(backgroundimage, bmpFactoryOptions);
return bitmap;
}
And i have passed the image width adn height as the parameter in this method.
bmLargeImage = ShrinkBitmap(backgroundimage, 7165, 786);