Getting current image from imageview (android) - java

I have an ImageView in which I load images from camera and gallery , and I do it using imgview.setimagebitmap(bitmap) ,( and I change the image again and again ) it works fine, but when I try to get the current image back for some processing (applying effect or rotate) it returns me the old image not the current one.
I think the problem is with imgview.setimagebitmap(bitmap).
can I be helped?
I have the following code:
try {
iv_image.buildDrawingCache();
Bitmap source = iv_image.getDrawingCache();
} catch(Exception ex) {
int a;
int b;
a = 11;
b = 12;
}

Can you please try to obtain the batman as follows :
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap()

Related

Java Android glide resize image [duplicate]

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.

SetImageUri showing no Image

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

Java android bitmap = null for certain images

I' making an android app which allows the user to take a photo and then the app will print some RGB value etc. I'm saving the pictures taken on the phone and then I make a bitmap out of those png files. I just found out that I should sleep the application for a moment in order for the image to be saved. But I'm still getting that the bitmap is null for some images I take. If I take an image of Rubik's cube with it's 6 different colors I almost never get the null pointer exception. But if I take a picture of the wall or something else the bitmap is = null.
Does anyone know what I should do in order to fix this?
Bitmap myBitmap;
final String dir =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) +
"/picFolder/";
try{
file = dir+Integer.toString(side)+".jpg";
File f = new File(file);
options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
myBitmap = BitmapFactory.decodeFile(file,options);
for(int i = 0; i<3; i++){
for(int j = 0; j<3; j++){
cube[side-1][i][j] = getColor(myBitmap, i, j);
}
}
}catch (Exception e){
Log.e("er0r", "HERE:::: " + e.toString());
}
I also faced the same problem when I was developing camera in my app.
For some images it was working fine and for some images it was showing null.
Later I found that is a size issue.
I fixed that issue like this,
private static Bitmap compressBitmap(Bitmap original) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
original.compress(Bitmap.CompressFormat.JPEG, 100, out);
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
return decoded;
}
Let me know if you need any other help.

Image from ACTION_IMAGE_CAPTURE Rotated

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.

Creating bitmap from canvas java

SOLUTION
Thanks to #ChandraSekhar's suggestions the issue was that I was passing in an Immutable Bitmap to the canvas constructor. The solution is to create a copy of it when using BitmapFactory.decodeFile();
Bitmap bmp = BitmapFactory.decodeFile(imageURL).copy(Bitmap.Config.ARGB_8888, true);
So I have a bitmap that I am using bitmapFactory.decodeFile() for and this works. I am able to create the bitmap, then I need to create a canvas and this is where things get weird.
Here's the flow of what is happening.
I capture an image, then pass it to functionA that sizes it, and saves it out and returns its file path. ( I am using Phonegap Cordova )
I then pass that URL back to my java and use the previously saved image and manipulate it in functionB
CODE IN QUESTION:
// GET URL TO IMAGE
final JSONObject options = optionsArr.optJSONObject(0);
String imageURL = options.optString("image");
// create image bitmap
Bitmap bmp = BitmapFactory.decodeFile(imageURL);
bmp = Bitmap.createBitmap(bmp,0,0,655,655);
/* Everything works fine until this point */
// create image canvas
Canvas canvas = new Canvas(bmp);
Bitmap one = Bitmap.createBitmap(bmp);
canvas.drawBitmap(one,0,0,null);
I receive no errors, it just hangs. Here's the kick in the pants - if I run another function say functionB first that one works but the other doesn't.
I thought maybe I needed to flush and close my first FileOutputStream, but that didn't seem to have any effect. I've tried different variable names for all elements, bitmaps, canvas, and fileoutputstreams.
here is an example of the full function...
NOTE: Because I am using phonegap / cordova I am returning a string
public String none(JSONArray optionsArr) {
// SET FILE PATH
String filePath = "";
File path = new File(Environment.getExternalStorageDirectory()+"/myApp/");
// TMP.jpg is where we store our temporary version of the image
File NewFilePath = new File(path, "tmp_NBB.jpg");
// CREATE FOLDERS IF NEEDED
try{
boolean success = false;
if(!path.exists()){
success = path.mkdir();
}
if (!success){
Log.d("NONE","Folder not created.");
}
else{
Log.d("NONE","Folder created!");
}
}
catch (Exception e){
e.printStackTrace();
}
// GET URL TO IMAGE
final JSONObject options = optionsArr.optJSONObject(0);
String imageURL = options.optString("image");
// create image bitmap
Bitmap bmp = BitmapFactory.decodeFile(imageURL);
bmp = Bitmap.createBitmap(bmp,0,0,655,655);
// create image canvas
Canvas canvas = new Canvas(bmp);
Bitmap none = Bitmap.createBitmap(bmp);
canvas.drawBitmap(none,0,0,null);
// SAVE IMAGE
try {
// OUTPUT STREAM
FileOutputStream out = new FileOutputStream(NewFilePath);
none.compress(Bitmap.CompressFormat.JPEG, 100, out);
// GET FILE PATH
Uri uri = Uri.fromFile(NewFilePath);
filePath = uri.toString();
try{
out.flush();
out.close();
// RETURN FILE PATH
return filePath;
}
catch (Exception e){
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return filePath;
}
Like I said this works for the first image, but when I attempt to open this image again, based on the returned filepath it chunks out at the create canvas line.
edit: The image path I am using looks like this:
/mtn/sdcard/myApp/tmp.jpg
thoughts?
Bitmap one = Bitmap.createBitmap(bmp);
In the above code bmp is a Bitmap and you are creating another Bitmap object one from bmp.
Remove that line and try by changing
canvas.drawBitmap(one,0,0,null);
to
canvas.drawBitmap(bmp,0,0,null);
Are you sure, the device on which you are running supports image size:655x655? Does bitmap get created?

Categories

Resources