Crop Imageview using input Specific Length and width - android

I have app. I want to crop my picture that shown in imageview. I want crop with spesific length and width. can you help me? I have code but, that code crop direct from gallery.
I just want crop imageview with spesific length and width. Where length and width just input manual from user.

If you don't mind adding a new Library to your project just to do image loading for you, you can easily add Glide to crop your local drawables or images from the web.
In your build.gradle (module app)
compile 'com.github.bumptech.glide:glide:3.6.0'
You can crop the image with this below:
final ImageView myImage = (ImageView) findViewById(R.id.myimageview);
final int myWidth = 210;
final int myHeight = 80;
Glide.with(getApplicationContext())
.load(R.drawable.example_drawable) // you can add any drawable or url of an image here
.asBitmap()
.into(new SimpleTarget<Bitmap>(myWidth, myHeight) {
#Override
public void onResourceReady(Bitmap bitmap, GlideAnimation anim) {
// Do something with bitmap here.
Bitmap bm = Bitmap.createBitmap(bitmap, 0, 0, myWidth, myHeight);
myImage.setImageBitmap(bm);
}
});

Related

Get bitmap from imageview in viewpager with glide

I'm showing in imageview with glide. User can save image on button click.
Bitmap bitmap = ((BitmapDrawable)imageViewPreview.getDrawable()).getBitmap();
when i use this code it save whole screen image(Image and black space).
imageViewPreview.setDrawingCacheEnabled(true);
imageViewPreview.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
imageViewPreview.layout(0, 0,
imageViewPreview.getMeasuredWidth(), imageViewPreview.getMeasuredHeight());
imageViewPreview.buildDrawingCache(true);
Bitmap bitmap = Bitmap.createBitmap(imageViewPreview.getDrawingCache());
imageViewPreview.setDrawingCacheEnabled(false);
when is use this, sometime it work but image get cropped in half or image go to up like "android:layout_alignParentTop="true".
You can get Bitmap from DrawingCache. After Settting image in ImageView you can get it as below:
imageViewPreview.setDrawingCacheEnabled(true);
imageViewPreview.buildDrawingCache(true);
final Bitmap bmp = Bitmap.createBitmap(layout.getDrawingCache());
imageViewPreview.setDrawingCacheEnabled(false);
If you need full size image then this is not right way i think .A better solution would be to get it From Glide as Bitmap . If full image was loaded already it will be quick (from cache) if not then it will load the full image from server or you can still use Drawing cache in case of No internet connection and glide failure.
Glide.with(imageView.getContext())
.asBitmap()
.load("imageUrl")
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
// Use resource here
}
});
}

How to get bitmap from imageView

I need to take an image from imageView and make it as a bitmap.
String s = getIntent().getStringExtra("ImageUri");
mImageViewFilter = (ImageView) findViewById(R.id.imageViewFilter);
Glide.with(this)
.load(s)
.into(mImageViewFilter);
Bitmap bitmap = ((BitmapDrawable)mImageViewFilter.getDrawable()).getBitmap();
You can see that into mImageViewFilter I am loading a photo with use of its URI and Glide library.
My next step is to take this photo which is in mImageViewFilter and make it as a bitmap. After the last line of code there is an exception. What am I doing wrong?
String s = getIntent().getStringExtra("ImageUri");
mImageViewFilter = (ImageView) findViewById(R.id.imageViewFilter);
To load image into ImageView use below code
Glide.with(this).load(s).into(mImageViewFilter);
So in order to get bitmap from ImageView (mImageViewFilter )
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
OR
You can add this before the code where you are trying to get Bitmap out of the ImageView
mImageViewFilter.setDrawingCacheEnabled(true);
In order to get the Bitmap out of the ImageView using DrawingCache, you first need to enable ImageView to draw image cache.
Bitmap bitmap = mImageViewFilter.getDrawingCache();
Actually you doing right thing. But the problem is Image loading is Asynchronous call.
And you called getBitmap() in right next line which will be called sequentially.
And it will give you null anyway cause image is not loaded yet .
Solution
if you want to do it in next direct step .You can use direct Bitmap callback.
Glide.with(this)
.asBitmap()
.load(path)
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
imageView.setImageBitmap(resource);
// Use resource as bitmap save it for later.
}
});
First take it as bitmap, then take it again to apply to our ImageView :
Bitmap bitmap = Glide.with(this) //taking as bitmap
.load(s)
.asBitmap()
.into(100, 100) //width and height
.get();
Glide.with(this) //apply to imageview
.load(s)
.into(mImageViewFilter);
The straightforward way to obtain a bitmap from any View including ImageView is to get the drawing cache from it.
mImageViewFilter.buildDrawingCache();
Bitmap bitmap = mImageViewFilter.getDrawingCache();
But the above method may give you a low quality image.
I think you should directly decode the bitmap from the Uri using BitmapFactory
InputStream in = context.getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(in);
in.close();

scaled bitmap according to device resolution

I am getting strange issue of White blank screen when i try to set image inside my image view after scaling it from bitmap.
I am getting random size images from server , I just need to show them in my image view without loose in quality of image. i have taken one layout and add image view dynamically through code.
Here is what i am doing in code :-
Getting Url form server and scaling it accordingly :-
url="http://www.petstory.co/attached_king_photos/hotel/7/attached_d67e2689e0d3370f7e76b5bba9f8e875e42a2e39.jpg"
AsyncTask task = new AsyncTask<String, String, Bitmap>() {
Bitmap bitmap = null;
#Override
protected Bitmap doInBackground(String... params) {
bitmap = getBitmapFromURL(params[0]);
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (result.getHeight() > 7000){
getResizedBitmap(result, 4000, 4000, image);
}else{
getResizedBitmap(result, 800, 800, image);
}
}
}.execute(imageUrl);
public Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight, final ImageView image) {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int width = bm.getWidth();
int height = bm.getHeight();
final int wantedgeightis = newHeight;
float scaleWidth = metrics.scaledDensity;
float scaleHeight = metrics.scaledDensity;
// float scaleWidth = ((float) newWidth) / width;
// float scaleHeight = ((float) newHeight) / height;
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap
matrix.setRectToRect(new RectF(0, 0, bm.getWidth(), bm.getHeight()), new RectF(0, 0, newWidth, newHeight), Matrix.ScaleToFit.CENTER);
final Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
// final Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
//
if (wantedgeightis == 4000) {
image.setScaleType(ImageView.ScaleType.FIT_XY);
image.setImageBitmap(resizedBitmap);
} else {
int bitmapWidth = resizedBitmap.getWidth();
int bitmapHeight = resizedBitmap.getHeight();
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, bitmapHeight);
image.setLayoutParams(params);
image.setPadding(10, 0, 10, 0);
image.setScaleType(ImageView.ScaleType.FIT_XY);
image.setImageBitmap(resizedBitmap);
}
}
});
return resizedBitmap;
}
The Url of image which i am setting in above methods is :-
http://www.petstory.co/attached_king_photos/hotel/7/attached_d67e2689e0d3370f7e76b5bba9f8e875e42a2e39.jpg
i am testing on nexus , rest images are aprearing as expected but only this image displays me white blank screen
I even make use of Glide and pisacco getting same issue for this image or sometimes highly distorted image get appear on screen.
Here is the code of Glide which i used :-
Glide.with(this) //passing context
.load(imageUrl) //passing your url to load image.
.placeholder(R.drawable.petzview_logo) //this would be your default image (like default profile or logo etc). it would be loaded at initial time and it will replace with your loaded image once glide successfully load image using url.
.error(R.drawable.petz_test)//in case of any glide exception or not able to download then this image will be appear . if you won't mention this error() then nothing to worry placeHolder image would be remain as it is.
.diskCacheStrategy(DiskCacheStrategy.ALL) //using to load into cache then second time it will load fast.
.fitCenter()//this method help to fit image into center of your ImageView
.dontAnimate()
.override(700, 4000)
.into(image);
I Even tried with bellow code too :-
Glide.with(this)
.load(imageUrl)
.skipMemoryCache(true)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.placeholder(R.drawable.petzview_logo)
.dontAnimate()
.fitCenter()
.into(new ViewTarget<ImageView, GlideDrawable>(image) {
#Override
public void onResourceReady(GlideDrawable resource, GlideAnimation anim) {
Toast.makeText(HowAboutHere.this, "success", Toast.LENGTH_LONG).show();
image.setImageDrawable(resource.getCurrent());
}
#Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
Toast.makeText(HowAboutHere.this, "Glide image load failed for %s -> %s" + e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
image.setVisibility(View.INVISIBLE);
}
});
By using .override(700, 4000) , the image is getting displayed but streched and if i change value to .override(700, 4100) , then blank white screen start getting displayed due to very large image size
Or Should i First Save image from URL to any file and then retrieve the image from file and apply inSample size bitmap algo on it this will be time taking and with utilize more memory and make application slow.As mentioned in below two links :-
Best method to download image from url in Android
Strange out of memory issue while loading an image to a Bitmap object
However here i am also posting the image look like when i use Bitmap code form displaying huge image from URL
As you can see the image is still getting stretched.
Any help will be appreciated
Thanks!!!

How to get image width and height from a network url

I am working on an android app and using REST APIs in it. I am receiving image urls from server and I want to show these images according to the original height of the image using image url.
How can I get the width and height of image using network image url. I have already tried getting bitmap from the string url but for this I want to perform this in background thread which leads the image loading very slow.
Is there any way I can get the image width and height from image url and can show the image in imageview according to the width and height.
Please help me if anyone know about this.
Thanks a lot in advanced.
URL url = new URL("url/image.jpg");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
for width:
bmp.getWidth();
for height:
bmp.getHeight();
for setting in imageview:
ImageView.setImageBitmap(bmp);
Further Reference:
https://developer.android.com/reference/android/graphics/Bitmap.html#getHeight%28%29
/* your library */
implementation 'com.github.bumptech.glide:glide:4.11.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
/* your code */
Glide.with(this)
.asBitmap() //get hieght and width
.load("link image")
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(#NonNull Bitmap resource, #Nullable
Transition<? super Bitmap> transition) {
Log.d("TAG", "onResourceReady: "+resource.getWidth()+"
"+resource.getHeight());
}
});
//////////////////////////////////////
Glide.with(this)
.asFile() // get size Image
.load("link image")
.into(new SimpleTarget<File>() {
#Override
public void onResourceReady(#NonNull File resource, #Nullable
Transition<? super File> transition) {
fab_full.setLabelText(""+resource.length());
}
});

OOM Error when loading Drawable

My Image has the size: 2480px x 3508px. I know that this is a very big image for android and so I try to resize it.
I'm using the PhotoView library too by the way.
Here i start resize the Image:
Drawable resizedDrawable = resize(getResources().getDrawable(R.drawable.handskizze), 50, 50);
skizze.setImageDrawable(resizedDrawable);
mAttacher = new PhotoViewAttacher(skizze);
The method which resizes the drawable:
private Drawable resize (Drawable image, int dstWith, int dstHeight) {
Bitmap b = ((BitmapDrawable)image).getBitmap();
Bitmap bitmapResized = Bitmap.createScaledBitmap(b,dstWith,dstHeight,false);
return new BitmapDrawable(getResources(),bitmapResized);
}
The Error:
at de.example.app.TouchMoveImage.onCreate(TouchMoveImage.java:70)
So why i can't resize the Image? I know that is it to big for android. But it crashes before it starts resizing.

Categories

Resources