I am aware of the sheer amount of answers regarding this. However, I had a simpler method which I would like to discuss with the larger community to see if there is a blindspot in my method.
Assuming you have a image filesize of 4MB, resolution of 4032 x 2268, and JPEG encoding.
You need a target image filesize of not more than 2MB, resolution to be scaled down accordingly and JPEG.
Image file size is calculated as such:
originFilesize = width x height x bytePerPixel x compressionRatio
targetFilesize = width" x height" x bytePerPixel x compressionRatio
compressionRatio is how well an image can be compressed. BytePerPixel will 3 for JPEG (RGB) and 4 for PNG (RGB + alpha channel)
Given that the content of originFilesize will be similar to targetFilesize (just the scaled down version) and the image encoding will be the same. We can assume that BytePerPixel and compressionRatio for both are the same.
This will give us the following:
originFilesize = width x height
targetFilesize = width" x height"
We can derive the resolution of our target image as such:
scaleRatio = targetFilesize/originFilesize
width" = width x scaleRatio
height" = height x scaleRatio
Here is the code in Kotlin:
val MB = 1024 * 1024
val scaleRatio = (2 * MB).toDouble() / originFile.length()
val newWidth = (bitmap.width * scaleRatio).toInt()
val newHeight = (bitmap.height * scaleRatio).toInt()
val scaledBitMap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true)
val bos = ByteArrayOutputStream()
bitmap.compress(CompressFormat.JPEG, 100, bos)
val targetFile = new FileOutputStream(targetFile)
targetFile.use {
it.write(bos)
}
Excuse me for the brevity of the code. I just put it all the necessary details. Here is one of the many test logs:
Original Filesize = 4374209 bytes
scaleRatio: 0.47943571054789563
File Dimension: 4032 x 2268
Scale File Dimension: 1933 x 1087
filesize saved is: 1690468 bytes
Consistently, I am getting less than 2MB which what I need. I also noticed that if I compressed to PNG, that will increase my image filesize. The final resized image size do have a smaller scale ratio (1690468/4374209 = 0.38 rather than 0.479). I suspect this comes from the assumption I made on compressionRatio.
Question now is whether there is a blindspot or flaw in this resize logics which I can't see?
I'm currently detecting the width and height of a selected video by doing the following:
MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(this, mVideoUri);
String height = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
String width = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
The activity in manifest:
<activity android:name=".TrimVideoActivity"
android:theme="#style/Theme.AppCompat.Light.NoActionBar.FullScreen"
/>
If I toast the the width and height it always returns w : 1920 h : 1080 no matter what the dimensions of the video are. I think it is returning the width and height of the device instead.
Is there something that I'm missing or doing wrong?
EDIT
By following the link that #VladMatvienko suggested I was able to get the correct width and height of the video file, this is how I implemented it:
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
Bitmap bmp = null;
retriever.setDataSource(this, mVideoUri);
bmp = retriever.getFrameAtTime();
String videoWidth = String.valueOf(bmp.getWidth());
String videoHeight = String.valueOf(bmp.getHeight());
Now I want to rotate the screen depending on the result (width/height), I tried it by doing the following:
int w = Integer.parseInt(videoWidth);
int h = Integer.parseInt(videoHeight);
if (w > h) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} if(w < h) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
But, the screen always gets rotated to landscape, instead of being set to portrait when the width is smaller than the height?
I decided to add a answer explaining how I fixed this issue.
The issue with my initial approach:
MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(this, mVideoUri);
String height = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
String width = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
The problem with this is that the video might not have the metadata that I'm looking for, which will result a nullpointerexception.
To avoid this issue I can get one frame from the video (as a bitmap) and get the width and height from that bitmap by doing the following:
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
Bitmap bmp;
retriever.setDataSource(this, mVideoUri);
bmp = retriever.getFrameAtTime();
But, this brings up another issue, that you might not have. In my case I would like to get the first/nearest frame to the start, because if the screen was rotated during the capturing of the video, then the width/height of the frame will change, so I just added 1 to getFrameAtTime(1).
Now I can rotate the screen depending of the width and height of my video file by doing:
try {
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
Bitmap bmp;
retriever.setDataSource(this, mVideoUri);
bmp = retriever.getFrameAtTime(1);
int videoWidth = bmp.getWidth();
int videoHeight = bmp.getHeight();
if (videoWidth > videoHeight) {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
if (videoWidth < videoHeight) {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}catch (RuntimeException ex){
Log.e("MediaMetadataRetriever", "- Failed to rotate the video");
}
Of course the above will be called from within onCreate.
Hope this helps someone out there.
I'm writing an app that uses the phone's camera to take a picture, and then display it. The problem is, for phones that have high-res cameras, this caused the app to crash, so I lowered the resolution using isSampleSize, which solved this issue. But now I have a problem with phones that have lower resolution cameras - the picture has terrible quality. Is there any way to check what the image memory consumption is, and according to that decide whether I want to lower the quality or not?
To rescale my picture, because I had a limitaion in the image height, I used the code below to resize it. But i didnt wan't to resize the bmp unless it was above my height requirement, hope you can use it. (Used a stream to get my pictures in)
if (stream != null) {
img = BitmapFactory.decodeStream(stream, null, o);
float imgHeight = (float) img.getHeight();
Display display = ((WindowManager) ctx.getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay();
float displayHeight = (float) (display.getHeight()-50);
if(imgHeight>displayHeight) {
float scaleFactor = displayHeight/imgHeight;
img = Bitmap.createScaledBitmap(img, (int)(img.getWidth()*scaleFactor), (int)(imgHeight*scaleFactor), false);
}
saveBitmap(new File(getSdPath() + location), img);
}
I'm loading a bitmap into an ImageView, and seeing this error. I gather this limit relates to a size limit for OpenGL hardware textures (2048x2048). The image I need to load is a pinch-zoom image of about 4,000 pixels high.
I've tried turning off hardware acceleration in the manifest, but no joy.
<application
android:hardwareAccelerated="false"
....
>
Is it possible to load an image larger than 2048 pixels into an ImageView?
This isn't a direct answer to the question (loading images >2048), but a possible solution for anyone experiencing the error.
In my case, the image was smaller than 2048 in both dimensions (1280x727 to be exact) and the issue was specifically experienced on a Galaxy Nexus. The image was in the drawable folder and none of the qualified folders. Android assumes drawables without a density qualifier are mdpi and scales them up or down for other densities, in this case scaled up 2x for xhdpi. Moving the culprit image to drawable-nodpi to prevent scaling solved the problem.
I have scaled down the image in this way:
ImageView iv = (ImageView)waypointListView.findViewById(R.id.waypoint_picker_photo);
Bitmap d = new BitmapDrawable(ctx.getResources() , w.photo.getAbsolutePath()).getBitmap();
int nh = (int) ( d.getHeight() * (512.0 / d.getWidth()) );
Bitmap scaled = Bitmap.createScaledBitmap(d, 512, nh, true);
iv.setImageBitmap(scaled);
All rendering is based on OpenGL, so no you can't go over this limit (GL_MAX_TEXTURE_SIZE depends on the device, but the minimum is 2048x2048, so any image lower than 2048x2048 will fit).
With such big images, if you want to zoom in out, and in a mobile, you should setup a system similar to what you see in google maps for example. With the image split in several pieces, and several definitions.
Or you could scale down the image before displaying it (see user1352407's answer on this question).
And also, be careful to which folder you put the image into, Android can automatically scale up images. Have a look at Pilot_51's answer below on this question.
Instead of spending hours upon hours trying to write/debug all this downsampling code manually, why not use Picasso? It was made for dealing with bitmaps of all types and/or sizes.
I have used this single line of code to remove my "bitmap too large...." problem:
Picasso.load(resourceId).fit().centerCrop().into(imageView);
Addition of the following 2 attributes in (AndroidManifest.xml) worked for me:
android:largeHeap="true"
android:hardwareAccelerated="false"
Changing the image file to drawable-nodpi folder from drawable folder worked for me.
I used Picasso and had the same problem. image was too large at least in on size, width or height. finally I found the solution here. you can scale the large image down according to display size and also keep the aspect ratio:
public Point getDisplaySize(Display display) {
Point size = new Point();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
display.getSize(size);
} else {
int width = display.getWidth();
int height = display.getHeight();
size = new Point(width, height);
}
return size;
}
and use this method for loading image by Picasso:
final Point displySize = getDisplaySize(getWindowManager().getDefaultDisplay());
final int size = (int) Math.ceil(Math.sqrt(displySize.x * displySize.y));
Picasso.with(this)
.load(urlSource)
.resize(size, size)
.centerInside()
.into(imageViewd);
also for better performance you can download the image according to width and height of the display screen, not whole the image:
public String reviseImageUrl(final Integer displayWidth, final Integer displayHeight,
final String originalImageUrl) {
final String revisedImageUrl;
if (displayWidth == null && displayHeight == null) {
revisedImageUrl = originalImageUrl;
} else {
final Uri.Builder uriBuilder = Uri.parse(originalImageUrl).buildUpon();
if (displayWidth != null && displayWidth > 0) {
uriBuilder.appendQueryParameter(QUERY_KEY_DISPLAY_WIDTH, String.valueOf(displayWidth));
}
if (displayHeight != null && displayHeight > 0) {
uriBuilder.appendQueryParameter(QUERY_KEY_DISPLAY_HEIGHT, String.valueOf(displayHeight));
}
revisedImageUrl = uriBuilder.toString();
}
return revisedImageUrl;
}
final String newImageUlr = reviseImageUrl(displySize.x, displySize.y, urlSource);
and then:
Picasso.with(this)
.load(newImageUlr)
.resize(size, size)
.centerInside()
.into(imageViewd);
EDIT: getDisplaySize()
display.getWidth()/getHeight() is deprecated. Instead of Display use DisplayMetrics.
public Point getDisplaySize(DisplayMetrics displayMetrics) {
int width = displayMetrics.widthPixels;
int height = displayMetrics.heightPixels;
return new Point(width, height);
}
BitmapRegionDecoder does the trick.
You can override onDraw(Canvas canvas), start a new Thread and decode the area visible to the user.
As pointed by Larcho, starting from API level 10, you can use BitmapRegionDecoder to load specific regions from an image and with that, you can accomplish to show a large image in high resolution by allocating in memory just the needed regions. I've recently developed a lib that provides the visualisation of large images with touch gesture handling. The source code and samples are available here.
View level
You can disable hardware acceleration for an individual view at runtime with the following code:
myView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
I ran through same problem, here is my solution. set the width of image same as android screen width and then scales the height
Bitmap myBitmap = BitmapFactory.decodeFile(image.getAbsolutePath());
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
Log.e("Screen width ", " "+width);
Log.e("Screen height ", " "+height);
Log.e("img width ", " "+myBitmap.getWidth());
Log.e("img height ", " "+myBitmap.getHeight());
float scaleHt =(float) width/myBitmap.getWidth();
Log.e("Scaled percent ", " "+scaleHt);
Bitmap scaled = Bitmap.createScaledBitmap(myBitmap, width, (int)(myBitmap.getWidth()*scaleHt), true);
myImage.setImageBitmap(scaled);
This is better for any size android screen. let me know if it works for you.
Scale down image:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
// Set height and width in options, does not return an image and no resource taken
BitmapFactory.decodeStream(imagefile, null, options);
int pow = 0;
while (options.outHeight >> pow > reqHeight || options.outWidth >> pow > reqWidth)
pow += 1;
options.inSampleSize = 1 << pow;
options.inJustDecodeBounds = false;
image = BitmapFactory.decodeStream(imagefile, null, options);
The image will be scaled down at the size of reqHeight and reqWidth. As I understand inSampleSize only take in a power of 2 values.
Use Glide library instead of directly loading into imageview
Glide : https://github.com/bumptech/glide
Glide.with(this).load(Uri.parse(filelocation))).into(img_selectPassportPic);
I tried all the solutions above, one-after-the-other, for quite many hours, and none seemed to work! Finally, I decided to look around for an official example concerning capturing images with Android's camera, and displaying them. The official example (here), finally gave me the only method that worked. Below I present the solution I found in that example app:
public void setThumbnailImageAndSave(final ImageView imgView, File imgFile) {
/* There isn't enough memory to open up more than a couple camera photos */
/* So pre-scale the target bitmap into which the file is decoded */
/* Get the size of the ImageView */
int targetW = imgView.getWidth();
int targetH = imgView.getHeight();
/* Get the size of the image */
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imgFile.getAbsolutePath(), bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
/* Figure out which way needs to be reduced less */
int scaleFactor = 1;
if ((targetW > 0) || (targetH > 0)) {
scaleFactor = Math.min(photoW/targetW, photoH/targetH);
}
/* Set bitmap options to scale the image decode target */
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
/* Decode the JPEG file into a Bitmap */
Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath(), bmOptions);
/* Associate the Bitmap to the ImageView */
imgView.setImageBitmap(bitmap);
imgView.setVisibility(View.VISIBLE);
}
NOTE FOR THOSE WHO WANT TO PUT IMAGES OF SMALL SIZE:
Pilot_51's solution (moving your images to drawable-nodpi folder) works, but has another problem:
It makes images TOO SMALL on screen unless the images are resized to a very large (like 2000 x 3800) resolution to fit screen -- then it makes your app heavier.
SOLUTION: put your image files in drawable-hdpi -- It worked like a charm for me.
Using the correct drawable subfolder solved it for me. My solution was to put my full resolution image (1920x1200) into the drawable-xhdpi folder, instead of the drawable folder.
I also put a scaled down image (1280x800) into the drawable-hdpi folder.
These two resolutions match the 2013 and 2012 Nexus 7 tablets I'm programming. I also tested the solution on some other tablets.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
///*
if (requestCode == PICK_FROM_FILE && resultCode == RESULT_OK && null != data){
uri = data.getData();
String[] prjection ={MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri,prjection,null,null,null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(prjection[0]);
ImagePath = cursor.getString(columnIndex);
cursor.close();
FixBitmap = BitmapFactory.decodeFile(ImagePath);
ShowSelectedImage = (ImageView)findViewById(R.id.imageView);
// FixBitmap = new BitmapDrawable(ImagePath);
int nh = (int) ( FixBitmap.getHeight() * (512.0 / FixBitmap.getWidth()) );
FixBitmap = Bitmap.createScaledBitmap(FixBitmap, 512, nh, true);
// ShowSelectedImage.setImageBitmap(BitmapFactory.decodeFile(ImagePath));
ShowSelectedImage.setImageBitmap(FixBitmap);
}
}
This code is work
Is there a way to get the dimensions of the image currently set in the ImageButton? I'm trying to achieve this.
I have a ImageButton with a default pic of 36 x 36. I then select an image of size say 200 x 200. I wanna call something like:
imageButton.setImageBitmap(Bitmap.createScaledBitmap(
bitmap, 36, 36, true));
to shrink the image to 36 x 36. Reason why I want to get the original image size is to cater for hdpi, mdpi and ldpi so I can set dimensions of the bitmap to 36 x 36, 24 x 24 and 18 x 18 respectively before adding it to the ImageButton. Any ideas?
Oh man, I got the answer after randomly fiddling with the code:
imageButton.getDrawable().getBounds().height();
imageButton.getDrawable().getBounds().width();
Try this code -
imageButton.getDrawable().getBounds().height();
imageButton.getDrawable().getBounds().width();
Maurice's answer didn't quite work for me, as I would frequently get 0 back, resulting in an Exception being thrown whenever trying to generate the scaled bitmap:
IllegalArgumentException: width and height must be > 0
I found a few other options if it helps anyone else.
Option 1
The imageButton is a View which means we can get the LayoutParams and take advantage of the built-in height and width properties. I found this from this other SO answer.
imageButton.getLayoutParams().width;
imageButton.getLayoutParams().height;
Option 2
Have our imageButton come from a Class which extends ImageButton, and then override View#onSizeChanged.
Option 3
Get the drawing rectangle on the view and use the width() and height() methods to get the dimensions:
android.graphics.Rect r = new android.graphics.Rect();
imageButton.getDrawingRect(r);
int rectW = r.width();
int rectH = r.height();
Combination
My final code ended up combining the three and selecting the max. I am doing this because I will get different results, depending on which phase the application is in (like when the View has not been fully drawn).
int targetW = imageButton.getDrawable().getBounds().width();
int targetH = imageButton.getDrawable().getBounds().height();
Log.d(TAG, "Calculated the Drawable ImageButton's height and width to be: "+targetH+", "+targetW);
int layoutW = imageButton.getLayoutParams().width;
int layoutH = imageButton.getLayoutParams().height;
Log.e(TAG, "Calculated the ImageButton's layout height and width to be: "+targetH+", "+targetW);
targetW = Math.max(targetW, layoutW);
targetH = Math.max(targetW, layoutH);
android.graphics.Rect r = new android.graphics.Rect();
imageButton.getDrawingRect(r);
int rectW = r.width();
int rectH = r.height();
Log.d(TAG, "Calculated the ImageButton's getDrawingRect to be: "+rectW+", "+rectH);
targetW = Math.max(targetW, rectW);
targetH = Math.max(targetH, rectH);
Log.d(TAG, "Requesting a scaled Bitmap of height and width: "+targetH+", "+targetW);
Bitmap scaledBmp = Bitmap.createScaledBitmap(bitmap, targetW, targetH, true);