I am working on an app that allows a user to draw within a confined canvas on a bitmap. Each drawing is created on a separate bitmap, which is then added to the main bitmap in the onDraw() method. This main bitmap needs to be larger than the screen dimensions so the user has plenty of room to draw a detailed scene. As such I also gave users the ability to pan/zoom on this main bitmap.
I noticed that this main bitmap size affects the performance of the device's drawing ability. The dimension have statically set at this point is 3000X3000, which works fine for my Galaxy 10.1 Pro tablet, but is VERY choppy on my low end Galaxy phone. This app is not meant to be used on phones, but the issue is still the same: how do I dynamically determine the dimensions for the main bitmap so that performance is consistent across devices?
If you want to see what the screen size is, do this. Docs here
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
Then you can use that information to resize the image.
You can set o.inJustDecodeBounds = true to get the image sizes without loading the image. If the image is to big, you can resize it. Example code below.
private Bitmap getBitmap(String path) {
Uri uri = getImageUri(path);
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
in = mContentResolver.openInputStream(uri);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Log.d(TAG, "scale = " + scale + ", orig-width: " + o.outWidth + ",
orig-height: " + o.outHeight);
Bitmap b = null;
in = mContentResolver.openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
o = new BitmapFactory.Options();
o.inSampleSize = scale;
b = BitmapFactory.decodeStream(in, null, o);
// resize to desired dimensions
int height = b.getHeight();
int width = b.getWidth();
Log.d(TAG, "1th scale operation dimenions - width: " + width + ",
height: " + height);
double y = Math.sqrt(IMAGE_MAX_SIZE
/ (((double) width) / height));
double x = (y / height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
(int) y, true);
b.recycle();
b = scaledBitmap;
System.gc();
} else {
b = BitmapFactory.decodeStream(in);
}
in.close();
Log.d(TAG, "bitmap size - width: " +b.getWidth() + ", height: " +
b.getHeight());
return b;
} catch (IOException e) {
Log.e(TAG, e.getMessage(),e);
return null;
}
Related
I'm creating a app that gets a image from camera (using CameraKit library), process the image and do a OCR Read using Google Vision Api, And get this error:
FATAL EXCEPTION: main
Process: com.., PID: 1938
java.lang.OutOfMemoryError: Failed to allocate a 63701004 byte
allocation with 16777216 free bytes and 60MB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.Bitmap.nativeCreate(Native Method)
at android.graphics.Bitmap.createBitmap(Bitmap.java:905)
at android.graphics.Bitmap.createBitmap(Bitmap.java:882)
at android.graphics.Bitmap.createBitmap(Bitmap.java:849)
at
com.****.****.Reader.ReaderResultActivity.createContrast(ReaderResultActivity.java:123)
at
com.*****.****.Reader.ReaderResultActivity.onCreate(ReaderResultActivity.java:47)
at android.app.Activity.performCreate(Activity.java:6672)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
ReaderResultActivity Code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reader_result);
ImageView img1 = (ImageView)findViewById(R.id.imageView2);
ImageView img2 = (ImageView)findViewById(R.id.imageView3);
ImageView img3 = (ImageView)findViewById(R.id.imageView4);
TextView scanResults = (TextView)findViewById(R.id.textView);
//Get bitmap from a static class.
Bitmap bitmap = Reader.img;
Bitmap grayScale = toGrayscale(bitmap);
Bitmap blackWhiteImage = createContrast(grayScale, 50);
Bitmap invertColor = invertColor(blackWhiteImage);
//Show process steps
img1.setImageBitmap(grayScale);
img2.setImageBitmap(blackWhiteImage);
img3.setImageBitmap(invertColor);
TextRecognizer detector = new TextRecognizer.Builder(getApplicationContext()).build();
try {
if (detector.isOperational()) {
Frame frame = new Frame.Builder().setBitmap(invertColor).build();
SparseArray<TextBlock> textBlocks = detector.detect(frame);
String blocks = "";
String lines = "";
String words = "";
for (int index = 0; index < textBlocks.size(); index++) {
//extract scanned text blocks here
TextBlock tBlock = textBlocks.valueAt(index);
blocks = blocks + tBlock.getValue() + "\n" + "\n";
for (Text line : tBlock.getComponents()) {
//extract scanned text lines here
lines = lines + line.getValue() + "\n";
for (Text element : line.getComponents()) {
//extract scanned text words here
words = words + element.getValue() + ", ";
}
}
}
if (textBlocks.size() == 0) {
scanResults.setText("Scan Failed: Found nothing to scan");
} else {
lines = lines.replaceAll("o", "0");
lines = lines.replaceAll("A", "1");
scanResults.setText(lines + "\n");
}
} else {
scanResults.setText("Could not set up the detector!");
}
} catch (Exception e) {
Toast.makeText(this, "Failed to load Image", Toast.LENGTH_SHORT)
.show();
Log.e("312", e.toString());
}
}
private Bitmap processImage(Bitmap bitmap){
Bitmap grayScale = toGrayscale(bitmap);
Bitmap blackWhiteImage = createContrast(grayScale, 50);
Bitmap invertColor = invertColor(blackWhiteImage);
return invertColor;
}
public Bitmap toGrayscale(Bitmap bmpOriginal) {
int width, height;
height = bmpOriginal.getHeight();
width = bmpOriginal.getWidth();
Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, bmpOriginal.getConfig());
Canvas c = new Canvas(bmpGrayscale);
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
paint.setColorFilter(f);
c.drawBitmap(bmpOriginal, 0, 0, paint);
return bmpGrayscale;
}
public static Bitmap createContrast(Bitmap src, double value) {
// image size
int width = src.getWidth();
int height = src.getHeight();
// create output bitmap
Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());
// color information
int A, R, G, B;
int pixel;
// get contrast value
double contrast = Math.pow((100 + value) / 100, 2);
// scan through all pixels
for(int x = 0; x < width; ++x) {
for(int y = 0; y < height; ++y) {
// get pixel color
pixel = src.getPixel(x, y);
A = Color.alpha(pixel);
// apply filter contrast for every channel R, G, B
R = Color.red(pixel);
R = (int)(((((R / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
if(R < 0) { R = 0; }
else if(R > 255) { R = 255; }
G = Color.red(pixel);
G = (int)(((((G / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
if(G < 0) { G = 0; }
else if(G > 255) { G = 255; }
B = Color.red(pixel);
B = (int)(((((B / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
if(B < 0) { B = 0; }
else if(B > 255) { B = 255; }
// set new pixel color to output bitmap
bmOut.setPixel(x, y, Color.argb(A, R, G, B));
}
}
return bmOut;
}
Bitmap invertColor(Bitmap src){
Bitmap copy = src.copy(src.getConfig(), true);
for (int x = 0; x < copy.getWidth(); ++x) {
for (int y = 0; y < copy.getHeight(); ++y) {
int color = copy.getPixel(x, y);
int r = Color.red(color);
int g = Color.green(color);
int b = Color.blue(color);
int avg = (r + g + b) / 3;
int newColor = Color.argb(255, 255 - avg, 255 - avg, 255 - avg);
copy.setPixel(x, y, newColor);
}
}
return copy;
}
Already try to do this in Manifest
android:largeHeap="true"
But the application just stop running when is on:
ReaderResultActivity.createContrast(ReaderResultActivity.java:123)
The same line that appears on error without the "largeHeap" tag.
Just dont know what to do, but i think that has something with all those "Bitmap.CreateBitmap" in every process function.
But without doing this, in OCR reading, appear a error saying that the bitmap has a wrong format.
You are loading three bitmaps in different imageviews without scaling it according to the size you want to show on your UI.
Android devices's camera captures pictures with much higher resolution than the screen density of your device.
Given that you are working with limited memory, ideally you only want to load a lower resolution version in memory. The lower resolution version should match the size of the UI component that displays it. An image with a higher resolution does not provide any visible benefit, but still takes up precious memory and incurs additional performance overhead due to additional on the fly scaling.
You can optimize it by following developer documentation suggestions - https://developer.android.com/topic/performance/graphics/load-bitmap.html
I'm using the barcode-reader example from Google's Android Vision API.
The preview size doesn't seem to fill up the whole space available (I'm using a Nexus 4 and there is a white unused space to the right of preview, about 1/3 of the width).
I would like to be able to run this example on various devices and always have it fill up the whole space available.
So the bit I've been playing with is:
CameraSource.Builder builder = new CameraSource.Builder(getApplicationContext(), barcodeDetector).setFacing(CameraSource.CAMERA_FACING_BACK).setRequestedPreviewSize(?, ?).setRequestedFps(15.0f);
Any ideas?
Thanks!
just remove or comment below code from CameraSourcePreview class
if (childHeight > layoutHeight) {
childHeight = layoutHeight;
childWidth = (int)(((float) layoutHeight / (float) height) * width);
}
and use layoutHeight instead of childHeight of "CameraSourcePreview" class in this loop - for (int i = 0; i < getChildCount(); ++i){...}
if (mCameraSource != null)
{
Size size = mCameraSource.getPreviewSize();
if (size != null)
{
width = size.getWidth();
height = size.getHeight();
}
}
// Swap width and height sizes when in portrait, since it will be rotated 90 degrees
if (isPortraitMode())
{
int tmp = width;
//noinspection SuspiciousNameCombination
width = height;
height = tmp;
}
final int layoutWidth = right - left;
final int layoutHeight = bottom - top;
// Computes height and width for potentially doing fit width.
int childWidth = layoutWidth;
int childHeight = (int) (((float) layoutWidth / (float) width) * height);
for (int i = 0; i < getChildCount(); ++i)
{
getChildAt(i).layout(0, 0, childWidth, layoutHeight);
}
try
{
startIfReady();
}
catch (SecurityException se)
{
Log.e(TAG, "Do not have permission to start the camera", se);
}
catch (IOException e)
{
Log.e(TAG, "Could not start camera source.", e);
}
}
There are two ways to make the camera image fill the entire screen.
Akesh Dubey's answer, which displays the whole image by stretching it to fit the layout's width and height. However, aspect ratio is not preserved.
My answer below, which crops the image to make it fit without sacrificing aspect ratio.
In order to crop-fit the image, all you have to do is change one > into a <. Find the below if-statement and change the condition like so:
if (childHeight < layoutHeight) {
childHeight = layoutHeight;
childWidth = (int)(((float) layoutHeight / (float) height) * width);
}
I am working on an android app, which has camera capture and photo uploading feature. If the device has a high resolution camera, the captured image size will be really large (1~3MB or more).
Since the app will need to upload this image to server, I will need to compress the image before uploading. If the camera captured a 1920x1080 full-res photo for example, the ideal output is to keep a 16:9 ratio of the image, compress it to be a 640x360 image to reduce some image quality and make it a smaller size in bytes.
Here is my code (referenced from google):
/**
* this class provide methods that can help compress the image size.
*
*/
public class ImageCompressHelper {
/**
* Calcuate how much to compress the image
* #param options
* #param reqWidth
* #param reqHeight
* #return
*/
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;
}
/**
* resize image to 480x800
* #param filePath
* #return
*/
public static Bitmap getSmallBitmap(String filePath) {
File file = new File(filePath);
long originalSize = file.length();
MyLogger.Verbose("Original image size is: " + originalSize + " bytes.");
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
// Calculate inSampleSize based on a preset ratio
options.inSampleSize = calculateInSampleSize(options, 480, 800);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap compressedImage = BitmapFactory.decodeFile(filePath, options);
MyLogger.Verbose("Compressed image size is " + sizeOf(compressedImage) + " bytes");
return compressedImage;
}
The problem with the above code is:
It cannot keep the ratio, the code is forcing the image to resized to 480x800. if user captured a image in another ratio, the image will not look good after compress.
It doesn't functioning well. The code will always change the image size to 7990272byte no matter what the original file size is. If the original image size is pretty small already, it will make it big (my test result to take a picture of my wall, which is pretty much mono-colored):
Original image size is: 990092 bytes.
Compressed image size is 7990272 bytes
I am asking if there's suggestion of a better way to compress photo so it can be uploaded smoothly?
You need to decide on a limit for either your width or height (not both, obviously). Then replace those fixed image sizes with calculated ones, say:
int targetWidth = 640; // your arbitrary fixed limit
int targetHeight = (int) (originalHeight * targetWidth / (double) originalWidth); // casts to avoid truncating
(Add checks and calculation alternatives for landscape / portrait orientation, as needed.)
As #harism also commented: the large size you mentioned is the raw size of that 480x800 bitmap, not the file size, which should be a JPEG in your case. How are you going about saving that bitmap, BTW? Your code doesn't seem to contain the saving part.
See this question here for help on that, with the key being something like:
OutputStream imagefile = new FileOutputStream("/your/file/name.jpg");
// Write 'bitmap' to file using JPEG and 80% quality hint for JPEG:
bitmap.compress(CompressFormat.JPEG, 80, imagefile);
Firstly i check the size of image then i compress image according to size and get compressed bitmap then send that bitmap to server
For Compressed bitmap call below funtion we have to pass image path in below funtion
public Bitmap get_Picture_bitmap(String imagePath) {
long size_file = getFileSize(new File(imagePath));
size_file = (size_file) / 1000;// in Kb now
int ample_size = 1;
if (size_file <= 250) {
System.out.println("SSSSS1111= " + size_file);
ample_size = 2;
} else if (size_file > 251 && size_file < 1500) {
System.out.println("SSSSS2222= " + size_file);
ample_size = 4;
} else if (size_file >= 1500 && size_file < 3000) {
System.out.println("SSSSS3333= " + size_file);
ample_size = 8;
} else if (size_file >= 3000 && size_file <= 4500) {
System.out.println("SSSSS4444= " + size_file);
ample_size = 12;
} else if (size_file >= 4500) {
System.out.println("SSSSS4444= " + size_file);
ample_size = 16;
}
Bitmap bitmap = null;
BitmapFactory.Options bitoption = new BitmapFactory.Options();
bitoption.inSampleSize = ample_size;
Bitmap bitmapPhoto = BitmapFactory.decodeFile(imagePath, bitoption);
ExifInterface exif = null;
try {
exif = new ExifInterface(imagePath);
} catch (IOException e) {
// Auto-generated catch block
e.printStackTrace();
}
int orientation = exif
.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
Matrix matrix = new Matrix();
if ((orientation == 3)) {
matrix.postRotate(180);
bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0,
bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix,
true);
} else if (orientation == 6) {
matrix.postRotate(90);
bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0,
bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix,
true);
} else if (orientation == 8) {
matrix.postRotate(270);
bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0,
bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix,
true);
} else {
matrix.postRotate(0);
bitmap = Bitmap.createBitmap(bitmapPhoto, 0, 0,
bitmapPhoto.getWidth(), bitmapPhoto.getHeight(), matrix,
true);
}
return bitmap;
}
getFileSize funtion for getting the size of image
public long getFileSize(final File file) {
if (file == null || !file.exists())
return 0;
if (!file.isDirectory())
return file.length();
final List<File> dirs = new LinkedList<File>();
dirs.add(file);
long result = 0;
while (!dirs.isEmpty()) {
final File dir = dirs.remove(0);
if (!dir.exists())
continue;
final File[] listFiles = dir.listFiles();
if (listFiles == null || listFiles.length == 0)
continue;
for (final File child : listFiles) {
result += child.length();
if (child.isDirectory())
dirs.add(child);
}
}
return result;
}
I'm trying to display an image having it's absolute path. I came upon this code on stackoverflow which should theoretically work, however I get error Bitmap too big to be uploaded into a texture on most images so I'm looking for another way to do it. Surprisingly there aren't any examples apart from this one on how to do it.
This is what I am trying:
Bitmap myBitmap = BitmapFactory.decodeFile(imagePath);
ImageView image = new ImageView(context);
image.setImageBitmap(myBitmap);
layout.addView(image);
By the way the images I'm working with have been taken with the default camera app so they don't have any uncommon format or size (and can be seen with no problem on the gallery app). How can I add them to my layout?
Just try to resize your image first by using below code and then set it into the ImageView:
public static Drawable GetDrawable(String newFileName)
{
File f;
BitmapFactory.Options o2;
Bitmap drawImage = null;
Drawable d = null;
try
{
f = new File(newFileName);
//decodes image and scales it to reduce memory consumption
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
o.inTempStorage = new byte[16 * 1024];
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
//The new size we want to scale to
final int REQUIRED_SIZE = 150;
//Find the correct scale value. It should be the power of 2.
int scale = 1;
while ((o.outWidth / scale / 2 >= REQUIRED_SIZE) && (o.outHeight / scale / 2 >= REQUIRED_SIZE))
scale *= 2;
//Decode with inSampleSize
o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
drawImage = BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
//Bitmap bmp = pictureDrawableToBitmap((PictureDrawable) drawable);
d = new BitmapDrawable(drawImage);
//drawImage.recycle();
//new BitmapWorkerTask
}
catch (FileNotFoundException e)
{
}
return d;
}
Use the above method as below:
imageView.setImageBitmap(myBitmap);
You might want to use a smaller sample size (inSampleSize) that fits the heap
First, create a bitmap that fits the heap, possibly slightly larger than the one you require
BitmapFactory.Options bounds = new BitmapFactory.Options();
this.bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, bounds);
if (bounds.outWidth == -1) { // TODO: Error }
int width = bounds.outWidth;
int height = bounds.outHeight;
boolean withinBounds = width <= maxWidth && height <= maxHeight;
if (!withinBounds) {
int newWidth = calculateNewWidth(int width, int height);
float sampleSizeF = (float) width / (float) newWidth;
int sampleSize = Math.round(sampleSizeF);
BitmapFactory.Options resample = new BitmapFactory.Options();
resample.inSampleSize = sampleSize;
bitmap = BitmapFactory.decodeFile(filePath, resample);
}
The second step is to call Bitmap.createScaledBitmap() to create a new bitmap to the exact resolution you require.
Make sure you clean up after the temporary bitmap to reclaim its memory. (Either let the variable go out of scope and let the GC deal with it, or call .recycle() on it if you are loading lots of images and are running tight on memory.)
I'm resizing an array of Bitmaps to a certain percentage of screen (So looks the same on all devices). Some of the bitmaps are sprites with + 256kb in size (explosions etc).
Obviously the VM is running out of memory once the bitmaps are converted twice, the bitmaps only convert at the beginning of the android application but it's still giving the error.
Can anyone tell me, is there a better, faster, more effcient way to return this peice of code as a bitmap.
Just out of curiosity are bitmap values passed by reference? (As in does the object parameter use the same line of memory for the same object?).
Anyhow's here is z code:
public Bitmap ResizeBitmap(Bitmap bitmap, float s_percentage, int frames, int viewport_width, int viewport_height)
{
float percentage = s_percentage / 100.0f;
float scale = viewport_width / 100 * percentage;
if(viewport_width < viewport_height)
{
scale = viewport_height / 100 * percentage;
}
int newWidth = (int) (bitmap.getWidth() * scale);
int newHeight = (int) (bitmap.getHeight() * scale);
if(newWidth <= 0 || newHeight <= 0)
{
// Extra check, for invalid width/height
Log.e("Function List, Resize Bitmap", "invalid dimension ("+newWidth+"x"+newHeight+")");
return bitmap;
}
//Round up to closet factor of total frames
int rW = (newWidth/frames)+1;
newWidth = rW*frames;
Bitmap newBitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, false);
return newBitmap;
}
To be in VM budget try to scale down your Bitmap like this.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile( filename, options );
options.inJustDecodeBounds = false;
options.inSampleSize = 4;
bitmap = BitmapFactory.decodeFile( filename, options );
if ( bitmap != null ) {
bitmap = Bitmap.createScaledBitmap( bitmap, width, height, false );
}
//Adjust SampleSize to values like 2, 4, 8 etc