Capture image using dynamic co-ordinates through the camera - android

I am making a camera based application, where I put a rectangular view over the camera.
When I capture an image using new Camera.PictureCallback(), I cropped that image so as it will get the part of the rectangle.
Well, its working fine.
Now I implemented View.OnTouchListener and using that I made the shape movable.
So, I need to capture the image with the final selection of the user, like where they place the rectangle.
Bitmap imageOriginal = BitmapFactory.decodeByteArray(data, 0, data.length); // 2560×1440
float scale = 1280 / 1000;
int left = (int) (scale * (imageOriginal.getWidth() - 250) / 2);
int top = (int) (scale * (imageOriginal.getHeight() - 616) / 2);
int width = (int) (scale * 750);
int height = (int) (scale * 616);
Bitmap imageConverted = Bitmap.createBitmap(imageOriginal, left, top, width, height, null, false);
This is the method i used to crop image.The values are hard corded to find the exact position.
Now i need values for that top ,bottom, height, width with the changing rectangle.
//My customView that used to draw that rectangle
public class CustomView extends View {
private Paint paint = new Paint();
public CustomView(Context context) {
super(context);
}
#Override
protected void onDraw(Canvas canvas) { // Override the onDraw() Method
super.onDraw(canvas);
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.GREEN);
paint.setStrokeWidth(10);
//center
int x0 = canvas.getWidth()/2;
int y0 = canvas.getHeight()/2;
int dx = canvas.getHeight()/3;
int dy = canvas.getHeight()/3;
//draw guide box
canvas.drawRect(x0-dx, y0-dy, x0+dx, y0+dy, paint);
}
}
//my picture callback code
Camera.PictureCallback mPicture = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
// Replacing the button after a photho was taken.
// File name of the image that we just took.
fileName = "IMG_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()).toString() + ".jpg";
// Creating the directory where to save the image. Sadly in older
// version of Android we can not get the Media catalog name
File mkDir = new File(sdRoot, dir);
mkDir.mkdirs();
// Main file where to save the data that we recive from the camera
File pictureFile = new File(sdRoot, dir + fileName);
// Cropping image with the corresponding co-ordinates and save in to a file
try {
Bitmap imageOriginal = BitmapFactory.decodeByteArray(data, 0, data.length); // 2560×1440
float scale = 1280 / 1000;
int left = (int) (scale * (imageOriginal.getWidth() - 250) / 2);
int top = (int) (scale * (imageOriginal.getHeight() - 616) / 2);
int width = (int) (scale * 750);
int height = (int) (scale * 616);
Bitmap imageConverted = Bitmap.createBitmap(imageOriginal, left, top, width, height, null, false);
FileOutputStream purge = new FileOutputStream(pictureFile);
imageConverted.compress(Bitmap.CompressFormat.JPEG, 100, purge);
purge.flush();
purge.close();
} catch (FileNotFoundException e) {
Log.d("DG_DEBUG", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("DG_DEBUG", "Error accessing file: " + e.getMessage());
}
// Adding Exif data for the orientation.
try {
ProjectManager.getInstance().settings.IMAGE_LOCATION = "/sdcard/" + dir + fileName;
exif = new ExifInterface(ProjectManager.getInstance().settings.IMAGE_LOCATION);
exif.setAttribute(ExifInterface.TAG_ORIENTATION, "" + orientation);
exif.saveAttributes();
mView.saveImage(dir + fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
};

For me, I take a image then crop according to dimension of the selected area of the image..
public void onPictureTaken(byte[] data, Camera camera) {
Bitmap imageOriginal = BitmapFactory.decodeByteArray(data, 0, data.length, null);
int width = imageOriginal.getWidth();
int height = imageOriginal.getHeight(); // for width
int narrowSize = Math.min(width, height); // for height
int differ = (int) Math.abs((imageOriginal.getHeight() - imageOriginal.getWidth()) / 2.0f); // for dimension
width = (width == narrowSize) ? 0 : differ;
height = (width == 0) ? differ : 0;
Matrix rotationMatrix = new Matrix();
rotationMatrix.postRotate(90); // for orientation
Bitmap imageCropped = Bitmap.createBitmap(imageOriginal, width, height, narrowSize, narrowSize, rotationMatrix, false);
}
Capture Image
Output Image

Your rectangle is mCustomView.getWidth()*2/3 pixels wide, and mCustomView.getHeight()*2/3 pixels high, and its left corner is at 1/6 of mCustomView.getWidth(), if I understand your post correctly.
public void onPictureTaken(byte[] data, Camera camera) {
//.../
Bitmap imageOriginal = BitmapFactory.decodeByteArray(data, 0, data.length);
int[] customViewPosition;
mCustomView.getLocationInWindow(customViewPosition);
int[] surfacePosition;
mSurfaceView.getLocationInWindow(surfacePosition);
float scale = imageOriginal.getWidth()/(float)mSurfaceView.getWidth();
int left = (int) scale*(customViewPosition[0] + mCustomView.getWidth()/6F - surfacePosition[0]);
int top = (int) scale*(customViewPosition[1] + mCustomView.getHeight()/6F - surfacePosition[1]);
int width = (int) scale*mCustomView.getWidth()*2/3;
int height = (int) scale*mCustomView.getHeight()*2/3;
Bitmap imageCropped = Bitmap.createBitmap(imageOriginal, left, top, width, height, null, false);
//.../
}

Related

how to put text on image bitmap at bottom?

What I Want: I want to add text at bottom of a image which I have chose from either gallery or camera.
Original Image
I added blue color strip to image at bottom
In that strip, I want to add some text exactly in middle.
What's the Problem:
I'm unable to position text exactly in middle of blue color strip.
For different images, text size changes. Some time it is very small, some time it is very big.
What I Tried: My code is like below.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ImageView mImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = findViewById(R.id.imageView);
}
public void openGallery(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 100);
}
public void openCamera(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 101);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null && resultCode == Activity.RESULT_OK) {
if (requestCode == 100) {
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media
.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
addStampToImage(bitmap);
} else if (requestCode == 101) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
addStampToImage(bitmap);
}
}
}
private void addStampToImage(Bitmap originalBitmap) {
int extraHeight = (int) (originalBitmap.getHeight() * 0.15);
Bitmap newBitmap = Bitmap.createBitmap(originalBitmap.getWidth(),
originalBitmap.getHeight() + extraHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(newBitmap);
canvas.drawColor(Color.BLUE);
canvas.drawBitmap(originalBitmap, 0, 0, null);
Resources resources = getResources();
float scale = resources.getDisplayMetrics().density;
Paint pText = new Paint();
pText.setColor(Color.WHITE);
pText.setTextSize((int) (20 * scale));
String text = "Maulik";
/*Rect r = new Rect();
canvas.getClipBounds(r);
int cHeight = r.height();
int cWidth = r.width();
pText.setTextAlign(Paint.Align.LEFT);
pText.getTextBounds(text, 0, text.length(), r);
float x = -r.left;
float y = cHeight / 2f + r.height() / 2f - r.bottom;
int minusSpace = (int) (canvas.getClipBounds().bottom * 0.07);
canvas.drawText(text, 0, canvas.getClipBounds().bottom - minusSpace, pText);*/
Rect bounds = new Rect();
pText.getTextBounds(text, 0, text.length(), bounds);
int x = (newBitmap.getWidth() - bounds.width())/6;
int y = (newBitmap.getHeight() + bounds.height())/5;
canvas.drawText(text, x * scale, y * scale, pText);
mImageView.setImageBitmap(newBitmap);
}
}
Any help will be appreciated!
Updated: 1st Aug 2018
Changes in addStampToImage method.
int extraHeight = (int) (originalBitmap.getHeight() * 0.15);
Rect textHeightWidth = new Rect();
pText.getTextBounds(fromWhichMode, 0, fromWhichMode.length(), textHeightWidth);
canvas.drawText(textToStamp, (canvas.getWidth() / 2) - (textHeightWidth.width() / 2),
originalBitmap.getHeight() + (extraHeight / 2) + (textHeightWidth.height() / 2),
pText);
Above changes giving me text in middle of blue strip. But core ISSUE remains same. i.e Text size changes with respect to different image sizes.
Check the below code:-
private void addStampToImage(Bitmap originalBitmap) {
int extraHeight = (int) (originalBitmap.getHeight() * 0.15);
Bitmap newBitmap = Bitmap.createBitmap(originalBitmap.getWidth(),
originalBitmap.getHeight() + extraHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(newBitmap);
canvas.drawColor(Color.BLUE);
canvas.drawBitmap(originalBitmap, 0, 0, null);
Resources resources = getResources();
float scale = resources.getDisplayMetrics().density;
String text = "Maulik";
Paint pText = new Paint();
pText.setColor(Color.WHITE);
setTextSizeForWidth(pText,(int) (originalBitmap.getHeight() * 0.10),text);
Rect bounds = new Rect();
pText.getTextBounds(text, 0, text.length(), bounds);
int x= ((newBitmap.getWidth()-(int)pText.measureText(text))/2);
int h=(extraHeight+bounds.height())/2;
int y=(originalBitmap.getHeight()+h);
canvas.drawText(text, x, y, pText);
imageView.setImageBitmap(newBitmap);
}
private void setTextSizeForWidth(Paint paint, float desiredHeight,
String text) {
// Pick a reasonably large value for the test. Larger values produce
// more accurate results, but may cause problems with hardware
// acceleration. But there are workarounds for that, too; refer to
// http://stackoverflow.com/questions/6253528/font-size-too-large-to-fit-in-cache
final float testTextSize = 48f;
// Get the bounds of the text, using our testTextSize.
paint.setTextSize(testTextSize);
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
// Calculate the desired size as a proportion of our testTextSize.
float desiredTextSize = testTextSize * desiredHeight / bounds.height();
// Set the paint for that size.
paint.setTextSize(desiredTextSize);
}
Edit:-
Instead of above addStampToImage method you can also use your updated addStampToImage method like below:-
private void addStampToImage(Bitmap originalBitmap) {
int extraHeight = (int) (originalBitmap.getHeight() * 0.15);
Bitmap newBitmap = Bitmap.createBitmap(originalBitmap.getWidth(),
originalBitmap.getHeight() + extraHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(newBitmap);
canvas.drawColor(Color.BLUE);
canvas.drawBitmap(originalBitmap, 0, 0, null);
Resources resources = getResources();
float scale = resources.getDisplayMetrics().density;
String text = "Maulik";
Paint pText = new Paint();
pText.setColor(Color.WHITE);
setTextSizeForWidth(pText,(int) (originalBitmap.getHeight() * 0.10),text);
Rect bounds = new Rect();
pText.getTextBounds(text, 0, text.length(), bounds);
Rect textHeightWidth = new Rect();
pText.getTextBounds(text, 0, text.length(), textHeightWidth);
canvas.drawText(text, (canvas.getWidth() / 2) - (textHeightWidth.width() / 2),
originalBitmap.getHeight() + (extraHeight / 2) + (textHeightWidth.height() / 2),
pText);
imageView.setImageBitmap(newBitmap);
}
try this one i think help to you
/**
* FOR WATER-MARK
*/
public static Bitmap waterMark(Bitmap src, String watermark, Point location, int color, int alpha, int size, boolean underline) {
int[] pixels = new int[100];
//get source image width and height
int widthSreen = src.getWidth(); // 1080L // 1920
int heightScreen = src.getHeight(); // 1343L // 2387
Bitmap result = Bitmap.createBitmap(widthSreen, heightScreen, src.getConfig());
//create canvas object
Canvas canvas = new Canvas(result);
//draw bitmap on canvas
canvas.drawBitmap(src, 0, 0, null);
//create paint object
Paint paint = new Paint();
// //apply color
// paint.setColor(color);
// //set transparency
// paint.setAlpha(alpha);
// //set text size
size = ((widthSreen * 5) / 100);
paint.setTextSize(size);
// paint.setAntiAlias(true);
// //set should be underlined or not
// paint.setUnderlineText(underline);
//
// //draw text on given location
// //canvas.drawText(watermark, w / 4, h / 2, paint);
Paint.FontMetrics fm = new Paint.FontMetrics();
paint.setColor(Color.WHITE);
// paint.setTextSize(18.0f);
paint.getFontMetrics(fm);
int margin = 5;
canvas.drawRect(50 - margin, 50 + fm.top - margin,
50 + paint.measureText(watermark) + margin, 50 + fm.bottom
+ margin, paint);
paint.setColor(Color.RED);
canvas.drawText(watermark, 50, 50, paint);
return result;
}
call this method on your onActivityResult
Bitmap bitmapp = waterMark(bitmap, your_string, p, Color.RED, 90, 90, true);

Cropping image by setting height dynamically

Guess a picture of man. (Head at top & legs at bottom) :P
I am setting height dynamically using layoutparam.
When I set height for instance 300,
It sets height from HEAD to 300 units toward legs of image.
What I want is to set height from LEGs to top 300 units.
imageView.setHeight()
Use this method in your java class:
private void scaleImage(ImageView view) throws NoSuchElementException {
// Get bitmap from the the ImageView.
Bitmap bitmap = null;
try {
Drawable drawing = view.getDrawable();
bitmap = ((BitmapDrawable) drawing).getBitmap();
} catch (NullPointerException e) {
throw new NoSuchElementException("No drawable on given view");
} catch (ClassCastException e) {
// Check bitmap is Ion drawable
// bitmap = Ion.with(view).getBitmap();
}
// Get current dimensions AND the desired bounding box
int width = 0;
try {
width = bitmap.getWidth();
} catch (NullPointerException e) {
throw new NoSuchElementException("Can't find bitmap on given view/drawable");
}
int height = bitmap.getHeight();
int bounding = dpToPx(150);// set height
Logger.i("Test", "original width = " + Integer.toString(width));
Logger.i("Test", "original height = " + Integer.toString(height));
Logger.i("Test", "bounding = " + Integer.toString(bounding));
// Determine how much to scale: the dimension requiring less scaling is
// closer to the its side. This way the image always stays inside your
// bounding box AND either x/y axis touches it.
float xScale = ((float) bounding) / width;
float yScale = ((float) bounding) / height;
float scale = (xScale <= yScale) ? xScale : yScale;
Logger.i("Test", "xScale = " + Float.toString(xScale));
Logger.i("Test", "yScale = " + Float.toString(yScale));
Logger.i("Test", "scale = " + Float.toString(scale));
// Create a matrix for the scaling and add the scaling data
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
// Create a new bitmap and convert it to a format understood by the ImageView
Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
width = scaledBitmap.getWidth(); // re-use
height = scaledBitmap.getHeight(); // re-use
BitmapDrawable result = new BitmapDrawable(scaledBitmap);
Logger.i("Test", "scaled width = " + Integer.toString(width));
Logger.i("Test", "scaled height = " + Integer.toString(height));
// Apply the scaled bitmap
view.setImageDrawable(result);
// Now change ImageView's dimensions to match the scaled image
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
params.width = width;
params.height = height;
view.setLayoutParams(params);
Logger.i("Test", "done");
}
private int dpToPx(int dp) {
float density = getApplicationContext().getResources().getDisplayMetrics().density;
return Math.round((float) dp * density);
}
Now, how to call this methord :
Bitmap bitmap;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImage);
imageView.setImageBitmap(bitmap);
scaleImage(imageView);// call your imageview
} catch (IOException e) {
e.printStackTrace();
}

android : drawing to canvas without stretching

I an trying to draw a bitmap to canvas. it results in stretching the bitmap. What i want is not to stretch if image small and crop the image if it is bigger than the display. How this can be achieved.
I have a custom drawable that extends DrawableWrapper
public class MyDrawable extends DrawableWrapper {
public MyDrawable(Drawable drawable) {
super(drawable);
}
public MyDrawable(final Context context, Bitmap bitmap) {
this(new BitmapDrawable(context.getResources(),bitmap));
}
I am having this code in boundsChnage()
protected void onBoundsChange(Rect bounds) {
mBitmap = Bitmap.createBitmap(bounds.width(), bounds.height(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(mBitmap);
super.draw(canvas);
}
This results in drawing a cropped part of the stretched drawable.
i think it will help you.
Bitmap scaleBitmap = scaleBitmap(bitmap);
RectF rectF = new RectF(0, (mHeight scaleBitmap.getHeight()),
scaleBitmap.getWidth(), scaleBitmap.getHeight());
canvas.drawBitmap(scaleBitmap, null, rectF, null);
private Bitmap scaleBitmap(Bitmap bm) {
int width = bm.getWidth();
int height = bm.getHeight();
Log.v("Pictures", "Width and height are " + width + "--" + height);
int mWidth = this.getResources().getDisplayMetrics().widthPixels;
int mHeight = this.getResources().getDisplayMetrics().heightPixels;
if (width > height) {
// landscape
int ratio = width / mWidth;
width = mWidth;
height = height / ratio;
} else if (height > width) {
// portrait
int ratio = height / mHeight;
height = mHeight;
width = width / ratio;
} else {
// square
height = mWidth;
width = mWidth;
}
Log.v("Pictures", "after scaling Width and height are " + width + "--" + height);
bm = Bitmap.createScaledBitmap(bm, width, height, true);
return bm;
}

Android scaling down a Bitmap based on SurfaceView

So I am trying to scale down a bitmap based on the size of a surface view I have written the following code
public Bitmap scaleBitMap(int width, int height, Bitmap b){
// scale down based on the size of the Surface view.
// width and height = canvas.getHeight(), canvas.getWidth();
// this should set the height and width of the bitmap based on a percentage
// the bit map is returned and then displayed by canvas.drawBitmap(scaleBitMap(canvas.getHeight(),canvas.getWidth(),bitmapHere)....
Bitmap bitmap = null;
try{
bitmap = Bitmap.createScaledBitmap(b, (height/100 * 10), (width/100 * 10), true);
}catch(Exception e){
}
return bitmap;
}
Ok so this code works! returns a scaled bitmap.
I am not sure what are you trying to do, but i have done similar thing before. This code scales bitmap to match screensize. Maybe it will help you.
public Bitmap scaleBitMap(int width, int height, Bitmap b){
// scale down based on the size of the Surface view.
// width and height = canvas.getHeight(), canvas.getWidth();
// this should set the height and width of the bitmap based on a percentage
// the bit map is returned and then displayed by canvas.drawBitmap(scaleBitMap(canvas.getHeight(),canvas.getWidth(),bitmapHere)....
Bitmap bitmap = null;
try{
float scaledvalues[] = scale(b.getWidth(), b.getHeight(), width, height);
bitmap = Bitmap.createScaledBitmap(b, scaledvalues[1], scaledvalues[0], true);
}catch(Exception e){
}
return bitmap;
}
public float[] scale(int bitmapWidth, int bitmapHeight, int viewWidth, int viewHeight){
float scaledheight = -1f;
float scaledwidth = -1f;
float scaledheightpros = -1f;
float scaledwidthpros = -1f;
float finalheight = -1f;
float finalwidth = -1f;
if(bitmapHeight > viewHeight){
scaledheight = bitmapHeight - viewHeight;
float s = scaledheight*100f;
scaledheightpros = s / 100f;
}
if(bitmapWidth > viewWidth){
scaledwidth = bitmapWidth - viewWidth;
float z = scaledwidth * 100f;
scaledwidthpros = z / bitmapWidth;
}
if(scaledheightpros > scaledwidthpros){
float a = bitmapHeight/100f;
float b = bitmapWidth/100f;
finalheight = bitmapHeight - (a * scaledheightpros);
finalwidth = bitmapWidth - (b * scaledheightpros);
}
else{
float a = bitmapHeight/100f;
float b = bitmapWidth/100f;
finalheight = bitmapHeight - (a * scaledwidthpros);
finalwidth = bitmapWidth - (b * scaledwidthpros);
}
float array[] = {finalwidth, finalheight};
return array;
}
It works.. but perhaps i should check my math!
here is the working code....
public Bitmap scaleBitMap(int width, int height, Bitmap b){
// scale down based on the size of the Surface view.
// width and height = canvas.getHeight(), canvas.getWidth();
// this should set the height and width of the bitmap based on a percentage
// the bit map is returned and then displayed by canvas.drawBitmap(scaleBitMap(canvas.getHeight(),canvas.getWidth(),bitmapHere)....
Bitmap bitmap = null;
try{
bitmap = (Bitmap) createScaledBitmap(b, (height/100 * 22), (width/100 * 22), false);
}catch(Exception e){
Log.d("Bitmap","Issue: "+e);
}
return bitmap;
}

Resizeing bitmap

Hie. I am working on the live wallpaper and I have got a problem. I am done with the parallax effect in my wallpaper. Now, the problem is the bitmap (i.e., the static background) of my live wallpaper, is not getting scaled properly. In some screens the width is proper but in some the bitmap (i.e., the background) appears only half way.
I have tried the density, windowmanager and the px to dp conversion.
None of them seem to work for me. Or may be my approach towards it is not in a proper manner.
I need help for the same.
Code Snippet
this._backgroundImage = BitmapFactory.decodeResource(context.getResources(),R.drawable.scene, options);
Bitmap background_image = Bitmap.createScaledBitmap(_backgroundImage, width, height, false);
canvas.drawBitmap(this.background_image, 0, 0, null);
I was using following methods sometimes back.. I dont know if these will be helpful for you or not .. please check if this works for you
float scale = getResources().getDisplayMetrics().density;
Display display = ((WindowManager) main.getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
int WIDTH = display.getWidth();
int HEIGHT = display.getHeight();
public static Drawable resizeDrawable(Drawable d, float scale) {
Drawable drawable = null;
if (d != null) {
try {
Bitmap bitmap1 = ((BitmapDrawable) d).getBitmap();
int width = 0;
int height = 0;
if (Math.min(WIDTH, HEIGHT) > 600) {
width = (int) (100 * scale + 0.5f);
height = (int) (100 * scale + 0.5f);
} else if (Math.min(WIDTH, HEIGHT) > 240) {
width = (int) (70 * scale + 0.5f);
height = (int) (70 * scale + 0.5f);
} else {
width = (int) (44 * scale + 0.5f);
height = (int) (44 * scale + 0.5f);
}
drawable = new BitmapDrawable(resizeBitmap(bitmap1,
width, height));
} catch (Exception e) {
e.printStackTrace();
}
}
return drawable;
}
please note that value used in if-else conditions in resizeDrawable method are just arbitrary values taken by trial n error (which suits my app).. you can try other values according to screens you are targeting
public static Bitmap resizeBitmap(final Bitmap bitmap, final int width,
final int height) {
final int oldWidth = bitmap.getWidth();
final int oldHeight = bitmap.getHeight();
final int newWidth = width;
final int newHeight = height;
// calculate the scale
final float scaleWidth = ((float) newWidth) / oldWidth;
final float scaleHeight = ((float) newHeight) / oldHeight;
// create a matrix for the manipulation
final Matrix matrix = new Matrix();
// resize the Bitmap
matrix.postScale(scaleWidth, scaleHeight);
// if you want to rotate the Bitmap
// recreate the new Bitmap
final Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
oldWidth, oldHeight, matrix, true);
return resizedBitmap;
}
Try this:
Bitmap resizedBitmap=Bitmap.createScaledBitmap(bb, newWidth, newHeight, false);
Tell me if it works.
You can use this to get the screen size and scale it accordingly.
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth(); // deprecated
int height = display.getHeight();

Categories

Resources