How to get the image detail (name, width, height, size, etc) which is selected in image view
I Generate ImageViewXML
<ImageView android:id="#+id/imageView" android:layout_width="match_parent" android:layout_height="match_parent"/>
and get a function to put selected image from folder to that ImageView
Uri uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
//Log.d(TAG, String.valueOf(bitmap));
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
Its all working correctly without bug, when i want to get the image detail, such as name by using String.valueOf(bitmap) but it return with : android.graphics.Bitmap#5280fcb4
How to get that image detail ?
Try this
Bitmap bitmap = ((BitmapDrawable)imageView.getBackground()).getBitmap();
int width = bitmap .getWidth();
int height = bitmap .getHeight();
Size of Image
Bitmap bitmap = ((BitmapDrawable)imageView.getBackground()).getBitmap();
ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytestream );
byte[] imageByte = bytestream .toByteArray();
long lengthbmp = imageByte .length;
String path = (String) imageView .getTag();
you can get the path of the image by this getTag() from that should get the name of image
Related
After implementing Camera2 Api for clicking image I am getting image in this listener
private ImageReader.OnImageAvailableListener imageAvailableListener = new ImageReader.OnImageAvailableListener() {
#Override
public void onImageAvailable(ImageReader reader) {
Image img = reader.acquireLatestImage();
final Image.Plane[] planes = img.getPlanes();
final ByteBuffer buffer = planes[0].getBuffer();
byte[] byteArray = new byte[buffer.remaining()];
buffer.get(byteArray);
bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
uri = getImageUri(getContext(), bmp);
}
};
I tried to parse the Image to Bitmap in order to get the image uri using this method
private Uri getImageUri(Context context, Bitmap inImage) {
this.saveToInternalStorage(inImage);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(context.getContentResolver(), inImage, "CAPTURE" + captureCount, null);
return Uri.parse(path);
}
But the image uri, which I get from above method, when I try to use it for displaying image in ImageView doesnot shows up any thing but I can see the clicked image in gallery.
Image uri which I get starts like external/**/<some number>
What I am trying to do is I want to get uri of clicked image and use
that uri to edit it.
If there is any other way to edit image may be like using bitmap or some other form pls do mention.
I use this photo filter from https://github.com/Zomato/AndroidPhotoFilters to develop my app
this is my code when i got IllegalStateExpression
Caused by: java.lang.IllegalStateException
at android.graphics.Bitmap.setPixels(Bitmap.java:1556)
at com.zomato.photofilters.imageprocessors.ImageProcessor.doBrightness(ImageProcessor.java:45)
at com.zomato.photofilters.imageprocessors.subfilters.BrightnessSubfilter.process(BrightnessSubfilter.java:28)
at com.zomato.photofilters.imageprocessors.Filter.processFilter(Filter.java:88)
at org.d3ifcool.photostation.PhotoEditorActivity.onCreate(PhotoEditorActivity.java:103)
at org.d3ifcool.photostation.PhotoEditorActivity.onCreate(PhotoEditorActivity.java:104)
on Bitmap image1 = mMyFilter.processFilter(mOriginalImage);
BitmapFactory.Options mOriginalOption = new BitmapFactory.Options();
mOriginalOption.inSampleSize = 2;
Bitmap mOriginalImage = BitmapFactory.decodeFile(selectedImagePath, mOriginalOption);
mMyFilter = SampleFilters.getBlueMessFilter();
Bitmap image1 = mMyFilter.processFilter(mOriginalImage);
loadFilter(image1);
But it'll success if i use this code
context = this.getApplicationContext();
Bitmap outputImage = mMyFilter.processFilter(Bitmap.createScaledBitmap(
BitmapFactory.decodeResource(
context.getResources(), R.drawable.ic_bg_main_activity), 640, 640, false));
loadFilter(outputImage);
And this the methode from the documentation
public Bitmap processFilter(Bitmap inputImage) {
Bitmap outputImage = inputImage;
if (outputImage != null) {
for (SubFilter subFilter : subFilters) {
try {
outputImage = subFilter.process(outputImage);
} catch (OutOfMemoryError oe) {
System.gc();
try {
outputImage = subFilter.process(outputImage);
} catch (OutOfMemoryError ignored) {
}
}
}
}
return outputImage;
}
Why cant i use the BitmapFactory.decodeFile?
I need to pick the image from SD Card, not from the drawable resouce.
Does .decodeFile and .decodeResource have a different type of Bitmap?
Sorry for my bad english
So, as the Bitmap returned by BitmapFactory.decodeFile is not null, your problem is with the processFilter method.
In the second example (the one you say it works), you create a scaled Bitmap before calling processFilter. So in order to solve your issue, you should probably do:
BitmapFactory.Options originalOption = new BitmapFactory.Options();
originalOption.inSampleSize = 2;
Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath, originalOption );
if (bitmap != null) {
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 640, 640, false);
mMyFilter = SampleFilters.getBlueMessFilter();
Bitmap image1 = mMyFilter.processFilter(scaledBitmap);
loadFilter(image1);
} else {
Log.e("Decode image", "Decoded Bitmap is null");
// Manage the error
}
Before applying filter you need to set its width and height for custom scaling then you can apply zomato(basic image processing library) filters on your bitmap image otherwise it will give you error.
public static void filterApply(Filter filter){
Bitmap bitmcopy = PhotoModel.getInstance().getPhotoCopyBitmap();
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmcopy, bitmcopy.getWidth()-1, bitmcopy.getHeight()-1, false);
filter.processFilter(scaledBitmap);
filterImage.setImageBitmap(scaledBitmap);
}
i M passing a bitmap from one activity to other, after taking the screen shot
Bitmap bitmap;
bitmap = takeScreenshot();
try {
//Write file
String filename = "bitmap.png";
FileOutputStream stream = this.openFileOutput(filename, Context.MODE_PRIVATE);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
bitmap.recycle();
//Pop intent
Intent in1 = new Intent(this, FinalImageShare.class);
in1.putExtra("image", filename);
startActivity(in1);
} catch (Exception e) {
e.printStackTrace();
}
here i am getting the image in other activity , the problem is that the tool bar height is also coming (i m hiding the toool bar by setVisibility, )i want to crop the image so that toolbar height wont come.TIA
imageView=(ImageView)findViewById(R.id.imageView);
String filename = getIntent().getStringExtra("image");
try {
FileInputStream is = this.openFileInput(filename);
bmp = BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
You can use createBitmap method, like so:
resizedbitmap = Bitmap.createBitmap(bitmap, 0, 0, yourwidth, yourheight);
Where bitmap is the bitmap you create, and resizedbitmap is the cropped one.
createBitmap() method takes as parameter in this case: bitmap, start X, start Y, width and height.
You can use those two methods to get your width and height:
bitmap.getWidth(), bitmap.getHeight()
Check also this link to learn about the createBitmap method:
Developer site
Or you can use the drawing cache property for this, like this :
View main = findViewById(R.id.view);
Bitmap screenshot;
main.setDrawingCacheEnabled(true);
screenshot = Bitmap.createBitmap(main.getDrawingCache());
main.setDrawingCacheEnabled(false);
Or similar to the last one, ctx.getWindow().getDecorView() View to get full screen bitmap cache:
View view = ctx.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
Bitmap bmap = view.getDrawingCache();
int contentViewTop = ctx.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop(); /* skip status bar in screenshot */
Storage.shareBitmapInfo = Bitmap.createBitmap(bmap, 0, contentViewTop, bmap.getWidth(), bmap.getHeight() - contentViewTop, null, true);
view.setDrawingCacheEnabled(false);
Hope this helps!
I want my code to resize the image before saving but I can't find anything about it on Google.
Could you help me please ?
This is the code (from Android doc) :
private void galleryAddPic() {
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
File f = new File(mCurrentPhotoPath);
picturePathForUpload = mCurrentPhotoPath;
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
After that, I have to upload it to a server.
Thanks a lot.
You can save Bitmap image following code
Bitmap photo = (Bitmap) "your Bitmap image";
photo = Bitmap.createScaledBitmap(photo, 100, 100, false);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "Imagename.jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
After reading the other answers and not finding exactly what I wanted, here's my approach at acquiring an appropriately scaled bitmap. This is an adaptation of Prabu's answer.
It makes sure your picture is scaled in a way that does not deform the dimensions of the photo:
public saveScaledPhotoToFile() {
//Convert your photo to a bitmap
Bitmap photoBm = (Bitmap) "your Bitmap image";
//get its orginal dimensions
int bmOriginalWidth = photoBm.getWidth();
int bmOriginalHeight = photoBm.getHeight();
double originalWidthToHeightRatio = 1.0 * bmOriginalWidth / bmOriginalHeight;
double originalHeightToWidthRatio = 1.0 * bmOriginalHeight / bmOriginalWidth;
//choose a maximum height
int maxHeight = 1024;
//choose a max width
int maxWidth = 1024;
//call the method to get the scaled bitmap
photoBm = getScaledBitmap(photoBm, bmOriginalWidth, bmOriginalHeight,
originalWidthToHeightRatio, originalHeightToWidthRatio,
maxHeight, maxWidth);
/**********THE REST OF THIS IS FROM Prabu's answer*******/
//create a byte array output stream to hold the photo's bytes
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
//compress the photo's bytes into the byte array output stream
photoBm.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
//construct a File object to save the scaled file to
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "Imagename.jpg");
//create the file
f.createNewFile();
//create an FileOutputStream on the created file
FileOutputStream fo = new FileOutputStream(f);
//write the photo's bytes to the file
fo.write(bytes.toByteArray());
//finish by closing the FileOutputStream
fo.close();
}
private static Bitmap getScaledBitmap(Bitmap bm, int bmOriginalWidth, int bmOriginalHeight, double originalWidthToHeightRatio, double originalHeightToWidthRatio, int maxHeight, int maxWidth) {
if(bmOriginalWidth > maxWidth || bmOriginalHeight > maxHeight) {
Log.v(TAG, format("RESIZING bitmap FROM %sx%s ", bmOriginalWidth, bmOriginalHeight));
if(bmOriginalWidth > bmOriginalHeight) {
bm = scaleDeminsFromWidth(bm, maxWidth, bmOriginalHeight, originalHeightToWidthRatio);
} else {
bm = scaleDeminsFromHeight(bm, maxHeight, bmOriginalHeight, originalWidthToHeightRatio);
}
Log.v(TAG, format("RESIZED bitmap TO %sx%s ", bm.getWidth(), bm.getHeight()));
}
return bm;
}
private static Bitmap scaleDeminsFromHeight(Bitmap bm, int maxHeight, int bmOriginalHeight, double originalWidthToHeightRatio) {
int newHeight = (int) Math.min(maxHeight, bmOriginalHeight * .55);
int newWidth = (int) (newHeight * originalWidthToHeightRatio);
bm = Bitmap.createScaledBitmap(bm, newWidth, newHeight, true);
return bm;
}
private static Bitmap scaleDeminsFromWidth(Bitmap bm, int maxWidth, int bmOriginalWidth, double originalHeightToWidthRatio) {
//scale the width
int newWidth = (int) Math.min(maxWidth, bmOriginalWidth * .75);
int newHeight = (int) (newWidth * originalHeightToWidthRatio);
bm = Bitmap.createScaledBitmap(bm, newWidth, newHeight, true);
return bm;
}
Here's a corresponding link to my GitHub Gist: https://gist.github.com/Lwdthe1/2d1cd0a12f30c18db698
First convert your image to bitmap then use this code:
Bitmap yourBitmap;
Bitmap resized = Bitmap.createScaledBitmap(yourBitmap, newWidth, newHeight, true);
See this it will be help full. In general if your are taking an image by camera using intent you will get the uri of image as result you read it as scale down image and store it in the same place
If you want to capture a full size image, then you have no choice but to save it to the sd cart and then change the size of the image.
If however thumbnail image is sufficient then there is no need to save it to SD card and you can extract it from the extras of the returned intent.
You can look at this guide I wrote for both methods of taking images using the build in camera Activity:
Guide: Android: Use Camera Activity for Thumbnail and Full Size Image
BitmapFactory.Options optionsSignature = new BitmapFactory.Options();
final Bitmap bitmapSignature = BitmapFactory.decodeFile(
fileUriSignature.getPath(), optionsSignature);
Bitmap resizedSignature = Bitmap.createScaledBitmap(
bitmapSignature, 256, 128, true);
signature.setImageBitmap(resizedSignature);
I need Thumbnail of an image . I only know about the name of image which is stored in SD card . Can anyone help me.
Try this.
final int THUMBSIZE = 64;
Bitmap ThumbImage = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(imagePath),
THUMBSIZE, THUMBSIZE);
Refer this for more details.
Using MediaStore.Images.Thumbnails you can query and get two kinds of thumbnails: MINI_KIND: 512 x 384 thumbnail MICRO_KIND: 96 x 96 thumbnail.
The advantage of using this call is that the thumbnails are cached by the MediaStore. So retrieval would be faster if the thumbnail was previously created.
byte[] imageData = null;
try
{
final int THUMBNAIL_SIZE = 64;
FileInputStream fis = new FileInputStream(fileName);
Bitmap imageBitmap = BitmapFactory.decodeStream(fis);
Float width = new Float(imageBitmap.getWidth());
Float height = new Float(imageBitmap.getHeight());
Float ratio = width/height;
imageBitmap = Bitmap.createScaledBitmap(imageBitmap, (int)(THUMBNAIL_SIZE * ratio), THUMBNAIL_SIZE, false);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
imageData = baos.toByteArray();
}
catch(Exception ex) {
}
If you like HQ thumbnails, so use [RapidDecoder][1] library. It is simple as follow:
import rapid.decoder.BitmapDecoder;
...
Bitmap bitmap = BitmapDecoder.from(getResources(), R.drawable.image)
.scale(width, height)
.useBuiltInDecoder(true)
.decode();
Don't forget to use builtin decoder if you want to scale down less than 50% and a HQ result.