How can I crop a bitmap for ImageView? - java

I know this should be simple , but android:scaleType="centerCrop" doesn't crop Image
I got image 1950 pixels wide and need it to be cropped by parent's width. But android:scaleType="centerCrop" doesn't crop Image. What do I need to do in layout to show only first 400 pixels, for instance or whatever screen/parent width is
Sorry for simple question - tried to Google it - only complicated questions there. And I'm new, so don't downvote please)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rl1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background_color">
<ImageView
android:id="#+id/ver_bottompanelprayer"
android:layout_width="match_parent"
android:layout_height="227px"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:scaleType="matrix"
android:background="#drawable/ver_bottom_panel_tiled_long" />
</RelativeLayout>
if there's only way is to programmaticaly crop it - please give me an advice with a method

Alright, I will paste the comment as answer :) ->
RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl1);
final Options bitmapOptions=new Options();
DisplayMetrics metrics = getResources().getDisplayMetrics();
bitmapOptions.inDensity = metrics.densityDpi;
bitmapOptions.inTargetDensity=1;
/*`final` modifier might be necessary for the Bitmap*/
Bitmap bmp= BitmapFactory.decodeResource(getResources(), R.drawable.ver_bottom_panel_tiled_long, bitmapOptions);
bmp.setDensity(Bitmap.DENSITY_NONE);
bmp = Bitmap.createBitmap(bmp, 0, 0, rl.getWidth(), bmp.getHeight());
Then in the code:
ImageView iv = (ImageView)v.findViewById(R.id.ver_bottompanelprayer);
if (iv != null){
iv.setImageBitmap(bmp);
}
Cheers :)

You can also crop image by programmatically using createBitmap.
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
bm = Bitmap.createBitmap(bm, 0, 0, 400, 400);
your_imageview.setImageBitmap(bm);
Here 400 is your width & height you can change as per your requirement.

Make it android:scaleType="fitStart" and for android:layout_height="400px"

You can do this programmatically (this ensures you get the right height/width):
ImageView image = (ImageView) findVieById(R.id.ver_bottompanelprayer);
DisplayMetrics dm = getResources().getDisplayMetrics();
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(1950, dm.heightPixels);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
image.setLayoutParams(params);
image.setScaleType(ScaleType.FIT_XY);

Related

How to convert the view into bitmap without adding into the UI in Android

I am using View in android and I need to convert this to Bitmap without adding this into the activity.
view.setDrawingCacheEnabled(true);
Bitmap bitmap= view.getDrawingCache();
It returns bitmap as null.
Also I have tried the method view.buildDrawingCache() but still getDrawingCache() return null.
Thanks in advance.
First you need to create empty bitmap and get canvas from it.
use below code for this
int w = WIDTH_PX, h = HEIGHT_PX;
Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);
Now you need to draw you view in this bitmap.
use below code for this
LinearLayout layout = new LinearLayout(getContext());
TextView textView = new TextView(getContext());
int padding = 4;
textView.setPadding(padding, padding, padding, padding);
textView.setVisibility(View.VISIBLE);
textView.setText("Hello how are you");
layout.addView(textView);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
layout.measure(canvas.getWidth(), canvas.getHeight());
layout.layout(0, 0, canvas.getWidth(), canvas.getHeight());
layout.draw(canvas);
now your view is converted into the bitmap (bmp).

Android Converting Ninepatch Resource To Bitmap

I have a 9 patch drawable as XML. When I try to use BitmapFactory.decode to get bitmap out of it, it returns null. Is there anyway to get a bitmap from this resource?
nine_patch.xml:
<?xml version="1.0" encoding="utf-8"?>
<nine-patch xmlns:android="http://schemas.android.com/apk/res/android"
android:src="#drawable/empty_icon_video" >
</nine-patch>
and the code is:
BitmapFactory.decodeResource(mResources, resId);
Bitmap bmp = Bitmap.createBitmap(yourWidth, yourHeight, Bitmap.Config.ARGB_8888);
Drawable drawable = getResources().getDrawable(R.drawable.resId);
Canvas canvas = new Canvas(bmp);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
Try this. Now the bitmap will be having the ninepatch drawn over it. You can supply a different width and height.
You need to use a NinePatchDrawable API here -
NinePatchDrawable npDrawable = (NinePatchDrawable)getResources().getDrawable(R.drawable.empty_icon_video);

combine two images which is overlay

Hello i have a two image view one with picture which is selected from camera and another imageview is only with TEXT like "Made Hawk Nelson" the image of two imageview is below
xml code is below
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="7"
android:scaleType="fitXY" >
<ImageView
android:id="#+id/imgSelectedPhoto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/txt_made_hawk_nelson"
android:layout_centerInParent="true" />
</RelativeLayout>
Above is half screen code and above image is also half screen
Now i want to save this picture can any body help me how can i do that? may be CANVAS will help me but i do not know how to do that so please can any body help me
You have the right idea. The canvas would be the simplest way of doing it.
But you have to understand first that those ImageViews are only on-screen representation and to create a Bitmap with those two images over-layered have little to do with the on-screen representation of it.
As in memory representations of the images you'll have Drawables (which are pre-scaled according to the screen size so their size will vary from device to device as per ldpi, mdpi, hdpi and xhdpi folders) and Bitmaps, which are absolute representations.
And all that I just said will vary as per your application and I won't be giving you the exact solution but explain you all the concepts:
Just as example, let's say you have both the background and the text as Bitmaps object, so your code would be:
// Init our overlay bitmap
Bitmap bmp = backgroundBitmap.copy(Bitmap.Config.ARGB_8888, true);
// Init the canvas
Canvas canvas = new Canvas(bmp);
// Draw the text on top of the canvas
canvas.drawBitmap(textBitmap, 0, 0, null);
// now bmp have the two overlayed:
you can (and should) do some math and use the values 0, 0 from the drawBitmap() method to center the text on the canvas.
Alternatively, if you have a drawable (e.g. getResources.getDrawable(R.drawable.bkgr); ) you can use the draw() method to draw to the canvas and use the getIntrinsicHeight and getIntrinsicWidth to create the bitmap using this method
happy coding!
Change the layout as
<Framelayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="7" >
<ImageView
android:id="#+id/imgSelectedPhoto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/txt_made_hawk_nelson"
android:layout_centerInParent="true" />
set setDrawingCacheEnabled(true); and create bitmap from it as.
Bitmap bitmap;
// frmCaptureThis is the root framelayout (this contains your imageviews)
View v1 = frmCaptureThis;
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
saveImgToSDcard(bitmap); // function to saves the image to sd card
this may Helps you , Here need to change function with Required String,and pass your Background drawable Image,
and Adjust font Size,TextColor,And Alignment Using Canvas And Create one Single Bitmap and check it.
private Bitmap getThumb(String strangle, String strnote, int width, int height) {
//Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.transperet_bg);
Bitmap bmOverlay = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmOverlay);
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setTextSize(20);
paint.setFlags(Paint.ANTI_ALIAS_FLAG);
// if the background image is defined in main.xml, omit this line
canvas.drawARGB(140, 0, 0, 0);
//canvas.drawBitmap(mBitmap, 0, 0, null);
// draw the text and the point
paint.setTextAlign(Paint.Align.LEFT);
canvas.drawText("Head Angel = " + strangle, 10, 20, paint);
strnote = edtnote.getText().toString();
if (TextUtils.isEmpty(strnote)) {
strnote = "Note";
}
canvas.drawText(strnote, 10, 50, paint);
paint.setTextAlign(Paint.Align.RIGHT);
canvas.drawText("www.moovemtb.com", width-60, 50, paint);
canvas.drawText("Head Angel App", width-60, 20, paint);
canvas.drawPoint(30.0f, height/2, paint);
return bmOverlay;
}
Please try this, it works well
BufferedImage img1 = ImageIO.read(new File(pathtoImage)); //first image
BufferedImage img2 = ImageIO.read(new File(pathtoOverlay)); //overlay text image
BufferedImage combinedImage = new BufferedImage(img1.getWidth(),img1.getHeight(),BufferedImage.TYPE_INT_RGB);
Graphics g = combinedImage.getGraphics();
g.drawImage(img1, 0, 0, null);
g.drawImage(img2, 0, 0, null);
ImageIO.write(combinedImage,"JPG",new File(pathToBeSaved,"combined.jpg");

Android What is the equivalent java code for `<item android:left="10dp">`?

What is the equivalent java code for <item android:left="10dp">?
To be more specific I am trying to get a Bitmap programatically that is equivalent to:
<item android:left="5dp" android:bottom="5dp">
<bitmap
android:src="#drawable/screw"
android:gravity="bottom|left" />
</item>
Edit
So far I got:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
Bitmap screw = BitmapFactory.decodeResource(res, resId, options);
BitmapDrawable s = new BitmapDrawable(res, screw);
s.setGravity(Gravity.LEFT|Gravity.BOTTOM);
You could inflate the view from xml pretty easily or if you are loading the drawables programmatically you should use the documentation: http://developer.android.com/reference/android/graphics/drawable/LayerDrawable.html
It has been a while since I worked with java/android but something like this.
Drawable[] layers = [drawable1, drawable2, etc]
LayerDrawable mDrawable = new LayerDrawable(layers);
//mDrawable.setLayerInset(int index, int left, int top, int right, int bottom)
//you will have to manually calculate density pixels.
mDrawable.setLayerInset(0, 5, 0, 0, 5)

OutOfMemory Exception when handling images [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
OutOfMemoryError: bitmap size exceeds VM budget :- Android
Im in the process of writing a program which uses images from the gallery and then displays them in an activity (one image pr. activity). However I've been bumping into this error over and over again for three days straight without doing any progress of eliminating it:
07-25 11:43:36.197: ERROR/AndroidRuntime(346): java.lang.OutOfMemoryError: bitmap size exceeds VM budget
My code flow is as follows:
When the user presses a button an intent is fired leading to the gallery:
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, 0);
Once the user has selected an image the image is presented in an imageview:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ImageView
android:background="#ffffffff"
android:id="#+id/image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:maxWidth="250dip"
android:maxHeight="250dip"
android:adjustViewBounds="true"/>
</LinearLayout>
In the onActivityResult method i have:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK) {
switch(requestCode) {
case 0: // Gallery
String realPath = getRealPathFromURI(data.getData());
File imgFile = new File(realPath);
Bitmap myBitmap;
try {
myBitmap = decodeFile(imgFile);
Bitmap rotatedBitmap = resolveOrientation(myBitmap);
img.setImageBitmap(rotatedBitmap);
OPTIONS_TYPE = 1;
} catch (IOException e) { e.printStackTrace(); }
insertImageInDB(realPath);
break;
case 1: // Camera
The decodeFile method is from here and the resolveOrientation method just wraps the bitmap into a matrix and turns it 90 degrees clockwise.
I really hope someone can help me resolve this matter.
it is because your bitmap size is large, so reduce the image size manually, or by programmatically
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap preview_bitmap = BitmapFactory.decodeFile(mPathName, options);
Your GC does not run. Try getting your Bitmap by pieces
BitmapFactory.Options buffer = new BitmapFactory.Options();
buffer.inSampleSize = 4;
Bitmap bmp = BitmapFactory.decodeFile(path, buffer);
There are many question in Stackoverflow about bitmap size exceeds VM budget so first search about your issue and when you cant find any solution then ask question here
The problem is because your bitmap's size is too large than the VM can handle. For example from your code I can see that you are trying to paste an Image into imageView which you are capturing using Camera. So normally the camera images will be too large in size which will rise this error obviously.
So as others have suggested, you have to compress your image either by sampling it or convert your image into smaller resolution.
For example if your imageView is 100x100 in width and height, you can create a scaled bitmap so that your imageView gets filled exactly. You can do this for that,
Bitmap newImage = Bitmap.createScaledBitmap(bm, 350, 300,true);
or you can sample it in methods what user hotveryspicy have suggested.

Categories