Image Scaling is not working properly - android

I am working on a complex UI design it is like circular wheel containing 10 icons in circular locus. i need to scale every icon as per the device resolution. Please have a look for specific code snippet:-
if (displayWidth<=241) {
bitmap = scaleBimtap(bitmap, 42, 39);
}else if (displayWidth<=320) {
bitmap = scaleBimtap(bitmap, 42, 39);
}else if (displayWidth<=480) {
bitmap = scaleBimtap(bitmap, 52, 44);
}else{
bitmap = scaleBimtap(bitmap, 52, 44);
}
HTC sensation is a 540X960 resolution device. So here is bitmap = scaleBimtap(bitmap, 52, 44); must be chosen in this case but this seems to be wrongly scaled and icons being displayed bigger then. What can i do for this to work.

Image from URL
imageView = new (ImageView)findViewById(R.id.myImage);
Get Image from Url
Bitmap originalBitmap = getBitmapFromURL("http://www.chennaionline.com/home.JPG");
getBitmapFromURL method:
public static 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;
}
}
Set bitmap
Bitmap bitmap = Bitmap.createScaledBitmap(originalBitmap, width,
height, false);
imageView.setImageBitmap(bitmap);
Image from Resource File
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();

Related

How to check if the bitmap has data?

What I have: I am downloading an image from a URL and converting it to a bitmap.
What is happening: Sometimes the server returns an image, other times just a small placeholder.
What I am trying to do: How to find out if the bitmap contains an image (the image is quite medium sized compared to the placeholder which is tiny).
Code used to get the image from the URL:
private Bitmap getBitmap(String url)
{
File f=fileCache.getFile(url);
//from SD cache
Bitmap b = decodeFile(f);
if(b!=null)
return b;
//from web
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}
Determinate minimum width and height of image and if bitmap height and width is smaller than this minimum, it means that is placeholder. For example
Bitmap bitmap = decodeFile(f);
int minHeight = 500;
int minWidth = 500;
if(bitmap.getHeight() < minHeight && bitmap.getWidth() < minWidth){
//it is a placeholder
}
if the placeholder is the same size every time then just replace 60 with it's height in pixels. This just takes a Bitmap and returns true if the Bitmap height matches your placeholder.
private bool isPlaceholder (Bitmap bmp)
{
//presumably, the placeholder never changes size
//if it's 60 then we've got a placeholder
if (bmp.Height == 60){
return true;
}
else{
return false;
}
}
EDIT: This only works if the placeholder is always smaller than the image. Otherwise you would perhaps need more complex logic like checking the height and size of the image in bytes. OR Height and Width. If it's always smaller in height then you can use something like above.

What is the specific difference between Bitmap from BitmapFactory.decodeFile and BitmapFactory.decodeResource in android

I use this photo filter from https://github.com/Zomato/AndroidPhotoFilters to develop my app
this is my code when i got IllegalStateExpression
Caused by: java.lang.IllegalStateException
at android.graphics.Bitmap.setPixels(Bitmap.java:1556)
at com.zomato.photofilters.imageprocessors.ImageProcessor.doBrightness(ImageProcessor.java:45)
at com.zomato.photofilters.imageprocessors.subfilters.BrightnessSubfilter.process(BrightnessSubfilter.java:28)
at com.zomato.photofilters.imageprocessors.Filter.processFilter(Filter.java:88)
at org.d3ifcool.photostation.PhotoEditorActivity.onCreate(PhotoEditorActivity.java:103)
at org.d3ifcool.photostation.PhotoEditorActivity.onCreate(PhotoEditorActivity.java:104)
on Bitmap image1 = mMyFilter.processFilter(mOriginalImage);
BitmapFactory.Options mOriginalOption = new BitmapFactory.Options();
mOriginalOption.inSampleSize = 2;
Bitmap mOriginalImage = BitmapFactory.decodeFile(selectedImagePath, mOriginalOption);
mMyFilter = SampleFilters.getBlueMessFilter();
Bitmap image1 = mMyFilter.processFilter(mOriginalImage);
loadFilter(image1);
But it'll success if i use this code
context = this.getApplicationContext();
Bitmap outputImage = mMyFilter.processFilter(Bitmap.createScaledBitmap(
BitmapFactory.decodeResource(
context.getResources(), R.drawable.ic_bg_main_activity), 640, 640, false));
loadFilter(outputImage);
And this the methode from the documentation
public Bitmap processFilter(Bitmap inputImage) {
Bitmap outputImage = inputImage;
if (outputImage != null) {
for (SubFilter subFilter : subFilters) {
try {
outputImage = subFilter.process(outputImage);
} catch (OutOfMemoryError oe) {
System.gc();
try {
outputImage = subFilter.process(outputImage);
} catch (OutOfMemoryError ignored) {
}
}
}
}
return outputImage;
}
Why cant i use the BitmapFactory.decodeFile?
I need to pick the image from SD Card, not from the drawable resouce.
Does .decodeFile and .decodeResource have a different type of Bitmap?
Sorry for my bad english
So, as the Bitmap returned by BitmapFactory.decodeFile is not null, your problem is with the processFilter method.
In the second example (the one you say it works), you create a scaled Bitmap before calling processFilter. So in order to solve your issue, you should probably do:
BitmapFactory.Options originalOption = new BitmapFactory.Options();
originalOption.inSampleSize = 2;
Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath, originalOption );
if (bitmap != null) {
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 640, 640, false);
mMyFilter = SampleFilters.getBlueMessFilter();
Bitmap image1 = mMyFilter.processFilter(scaledBitmap);
loadFilter(image1);
} else {
Log.e("Decode image", "Decoded Bitmap is null");
// Manage the error
}
Before applying filter you need to set its width and height for custom scaling then you can apply zomato(basic image processing library) filters on your bitmap image otherwise it will give you error.
public static void filterApply(Filter filter){
Bitmap bitmcopy = PhotoModel.getInstance().getPhotoCopyBitmap();
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmcopy, bitmcopy.getWidth()-1, bitmcopy.getHeight()-1, false);
filter.processFilter(scaledBitmap);
filterImage.setImageBitmap(scaledBitmap);
}

Cropping Image view

i M passing a bitmap from one activity to other, after taking the screen shot
Bitmap bitmap;
bitmap = takeScreenshot();
try {
//Write file
String filename = "bitmap.png";
FileOutputStream stream = this.openFileOutput(filename, Context.MODE_PRIVATE);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
bitmap.recycle();
//Pop intent
Intent in1 = new Intent(this, FinalImageShare.class);
in1.putExtra("image", filename);
startActivity(in1);
} catch (Exception e) {
e.printStackTrace();
}
here i am getting the image in other activity , the problem is that the tool bar height is also coming (i m hiding the toool bar by setVisibility, )i want to crop the image so that toolbar height wont come.TIA
imageView=(ImageView)findViewById(R.id.imageView);
String filename = getIntent().getStringExtra("image");
try {
FileInputStream is = this.openFileInput(filename);
bmp = BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
You can use createBitmap method, like so:
resizedbitmap = Bitmap.createBitmap(bitmap, 0, 0, yourwidth, yourheight);
Where bitmap is the bitmap you create, and resizedbitmap is the cropped one.
createBitmap() method takes as parameter in this case: bitmap, start X, start Y, width and height.
You can use those two methods to get your width and height:
bitmap.getWidth(), bitmap.getHeight()
Check also this link to learn about the createBitmap method:
Developer site
Or you can use the drawing cache property for this, like this :
View main = findViewById(R.id.view);
Bitmap screenshot;
main.setDrawingCacheEnabled(true);
screenshot = Bitmap.createBitmap(main.getDrawingCache());
main.setDrawingCacheEnabled(false);
Or similar to the last one, ctx.getWindow().getDecorView() View to get full screen bitmap cache:
View view = ctx.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
Bitmap bmap = view.getDrawingCache();
int contentViewTop = ctx.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop(); /* skip status bar in screenshot */
Storage.shareBitmapInfo = Bitmap.createBitmap(bmap, 0, contentViewTop, bmap.getWidth(), bmap.getHeight() - contentViewTop, null, true);
view.setDrawingCacheEnabled(false);
Hope this helps!

scaled image not visible in android

I have to make an application in which i am downloading an image from a URL and i have to show the image to after scaling.
The default size of the image is 220x200
Scaled size of image is 55x50
Here is my code for doing the above:
XML file layout:
<ImageView android:id="#+id/productimage"
android:layout_gravity="center_vertical|left" android:layout_width="55dip"
android:layout_height="50dip" android:adjustViewBounds="true" />
Here is the code for downloading the image and resizing it:
ImageView productImage = (ImageView) arg1
.findViewById(R.id.productimage);
if (!headerDetails[1].equals("null")) {
Bitmap image = getImage(headerDetails[1]);
if (image != null) {
try {
productImage
.setImageBitmap(Bitmap
.createScaledBitmap(
image,
productImage
.getMeasuredWidth(),
productImage
.getMeasuredHeight(),
false));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here is the class for downloading the image:
private Bitmap getImage(String address) {
try {
Log.i("getimage", address);
URL url = new URL(address);
URLConnection conn = url.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bm = BitmapFactory.decodeStream(bis);
// bis.close();
// is.close();
return bm;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
No exception is being thrown here, hence the image is being downloaded correctly.
OUTPUT: No image is displayed in the imageview.
what am i doing wrong. The size of the image that i want is 55x50 but the size of the image on the net may vary.
thank you in advance.
EDIT:
the bitmap formed after the following code:
Bitmap bm = BitmapFactory.decodeStream(bis);
does not have a height and a width and it's height and width is set to -1. What could be going wrong here?
The following exception is also being thrown:
06-23 14:24:41.635: WARN/System.err(16618): java.lang.IllegalArgumentException: width and height must be > 0
I used this code to scale the bitmap:
Bitmap selectedImage = BitmapFactory.decodeFile(selectedImagePath);
image.setImageBitmap(Bitmap.createScaledBitmap(selectedImage,75, 75, true));
Try adding android:scaleType="fix_xy" to the imageview. Another error I found in your code is that you are getting the height and width in a wrong way. Try this:
imageView.getLayoutParams().height;
imageView.getLayoutParams().width;

How to set a bitmap from resource

This seems simple, I am trying to set a bitmap image but from the resources, I have within the application in the drawable folder.
bm = BitmapFactory.decodeResource(null, R.id.image);
Is this correct?
Assuming you are calling this in an Activity class
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.image);
The first parameter, Resources, is required. It is normally obtainable in any Context (and subclasses like Activity).
Try this
This is from sdcard
ImageView image = (ImageView) findViewById(R.id.test_image);
Bitmap bMap = BitmapFactory.decodeFile("/sdcard/test2.png");
image.setImageBitmap(bMap);
This is from resources
Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
If the resource is showing and is a view, you can also capture it. Like a screenshot:
View rootView = ((View) findViewById(R.id.yourView)).getRootView();
rootView.setDrawingCacheEnabled(true);
rootView.layout(0, 0, rootView.getWidth(), rootView.getHeight());
rootView.buildDrawingCache();
Bitmap bm = Bitmap.createBitmap(rootView.getDrawingCache());
rootView.setDrawingCacheEnabled(false);
This actually grabs the whole layout but you can alter as you wish.
If you have declare a bitmap object and you want to display it or store this bitmap object. but first you have to assign any image , and you may use the button click event, this code will only demonstrate that how to store the drawable image in bitmap Object.
Bitmap contact_pic = BitmapFactory.decodeResource(
v.getContext().getResources(),
R.drawable.android_logo
);
Now you can use this bitmap object, whether you want to store it, or to use it in google maps while drawing a pic on fixed latitude and longitude, or to use some where else
just replace this line
bm = BitmapFactory.decodeResource(null, R.id.image);
with
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.YourImageName);
I mean to say just change null value with getResources() If you use this code in any button or Image view click event just append getApplicationContext() before getResources()..
Using this function you can get Image Bitmap. Just pass image url
public Bitmap getBitmapFromURL(String strURL) {
try {
URL url = new URL(strURL);
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;
}
}

Categories

Resources