I'm loading images from URLS that are varying sizes. It seems the smaller ones come through, and a nullPointerException (displayed in the Log.d below) comes through for the larger ones. How can I get these images to resize?
BitmapDrawable drawable = null;
Bitmap bitmap = null;
try {
bitmap = loadBitmapFromWeb(url);
System.out.println("url " + url);
} catch (IOException e) {
}
int width = 150;
int height = 150;
try {
drawable = resizeImage(bitmap, height, width);
} catch (Exception e) {
Log.d("exception image", e.toString());
drawable = getDrawableFromResource(R.drawable.default_backup);
}
This is what I use to load from a URL:
public static Bitmap loadBitmapFromWeb(String url) throws IOException {
InputStream is = (InputStream) new URL(url).getContent();
Bitmap bitmap = BitmapFactory.decodeStream(is);
return bitmap;
}
This is what I use to resize, where the error appears:
public static BitmapDrawable resizeImage(Bitmap bitmap, int w, int h) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int newWidth = w;
int newHeight = h;
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height,
matrix, true);
return new BitmapDrawable(resizedBitmap);
}
Why don't you use available Bitmap function to do the resize. Supposing you downloaded correct image, you just need to do the following:
Bitmap scaledImage = Bitmap.createScaledBitmap(originalImage, newWidth, newHeight, false);
Related
Hello i have facebook image that i have to compress and put it in my imageview. I used below code to resize my image and compress it so that i can show it in my imageview but it gives file not found exception error
i do not find any way to compress file/image that located on server.
you can take bitmap from URL and the you suppose to re size.
For Getting Bitmap From URL.
URL url = new URL("http://....");
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
for resize you can use below code
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
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
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
How to use :-
place this code:-
private void showImage(final String URL) {
new Thread(new Runnable() {
#Override
public void run() {
URL url = new URL(URL);
Bitmap bm = BitmapFactory.decodeStream(url.openConnection()
.getInputStream());
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) YOUR_WIDTH) / width;
float scaleHeight = ((float) YOUR_HEIGHT) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// "RECREATE" THE NEW BITMAP
final Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width,
height, matrix, false);
runOnUiThread(new Runnable() {
#Override
public void run() {
your_imageView.setImageBitmap(resizedBitmap);
}
})
}
}).start();
}
thanks.
I am trying to resize a bitmap to custom X and Y and the code I am using runs sometimes into OutOfMemory exception. I looked here around and found some solutions how to use InputStream to resize bitmaps, but I was not able to find any approach how to resize it to custom X and Y dimensions . Could somebody give me an advice?
here is my code:
try {
Point scr = Sys.screenSize(getActivity());
// MY CUSTOM X and Y
int newWidth = (int) Sys.convertDpToPixel(linheight, getActivity())
* lines;
int newHeight = scr.x;
Bitmap bitmap = BitmapFactory.decodeResource(getActivity()
.getResources(), R.drawable.field);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
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
bm = Bitmap
.createBitmap(bitmap, 0, 0, width, height, matrix, false);
bitmap.recycle();
matrix = null;
iv.setImageBitmap(bm);
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
I think what you want is createScaledBitmap:
Bitmap resizedBitmap =
Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, false);
I am developing a application in which I want to resize captured image before store it in specified folder of sdcard.
I have used all the permissions required for write the data in sdcard but still I am unable to do it.
my code:
try{
Bitmap bitmap = Constant.decodeFile(fileName);
bitmap = Bitmap.createScaledBitmap(bitmap, 480, 320, true);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes);
File f = new File(fileName.toString());
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
}catch (Exception e) {
e.printStackTrace();
}catch (OutOfMemoryError o) {
o.printStackTrace();
}
You have forgot to flush the Stream after writing data into into. use FileOutputStream.flush() after writing data... and
try this...
File file = new File(fileName.toString());
try {
FileOutputStream stream = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 100, stream);
stream.flush();
stream.close();
} catch (Exception e) {
// TODO: handle exception
}
You can use createBitmap() to resize the original image.
FOllowing are the parameters:
(Bitmap source, int x, int y, int width, int height)
source The bitmap we are subsetting
x The x coordinate of the first pixel in source
y The y coordinate of the first pixel in source
width The number of pixels in each row
height The number of rows
Example:
Bitmap newbitmap = Bitmap.createBitmap(originalBitmap, 2, 2, bitmap.getWidth() - 4, bitmap.getHeight() - 120);
There is a nice tutorial on resizing images:
BitmapScaler scaler = new BitmapScaler(getResources(), R.drawable.moorwen, newWidth);
imageView.setImageBitmap(scaler.getScaled());
BitmapScaler class follows:
class BitmapScaler {
private static class Size {
int sample;
float scale;
}
private Bitmap scaled;
BitmapScaler(Resources resources, int resId, int newWidth)
throws IOException {
Size size = getRoughSize(resources, resId, newWidth);
roughScaleImage(resources, resId, size);
scaleImage(newWidth);
}
BitmapScaler(File file, int newWidth) throws IOException {
InputStream is = null;
try {
is = new FileInputStream(file);
Size size = getRoughSize(is, newWidth);
try {
is = new FileInputStream(file);
roughScaleImage(is, size);
scaleImage(newWidth);
} finally {
is.close();
}
} finally {
is.close();
}
}
BitmapScaler(AssetManager manager, String assetName, int newWidth)
throws IOException {
InputStream is = null;
try {
is = manager.open(assetName);
Size size = getRoughSize(is, newWidth);
try {
is = manager.open(assetName);
roughScaleImage(is, size);
scaleImage(newWidth);
} finally {
is.close();
}
} finally {
is.close();
}
}
Bitmap getScaled() {
return scaled;
}
private void scaleImage(int newWidth) {
int width = scaled.getWidth();
int height = scaled.getHeight();
float scaleWidth = ((float) newWidth) / width;
float ratio = ((float) scaled.getWidth()) / newWidth;
int newHeight = (int) (height / ratio);
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
scaled = Bitmap.createBitmap(scaled, 0, 0, width, height, matrix, true);
}
private void roughScaleImage(InputStream is, Size size) {
Matrix matrix = new Matrix();
matrix.postScale(size.scale, size.scale);
BitmapFactory.Options scaledOpts = new BitmapFactory.Options();
scaledOpts.inSampleSize = size.sample;
scaled = BitmapFactory.decodeStream(is, null, scaledOpts);
}
private void roughScaleImage(Resources resources, int resId, Size size) {
Matrix matrix = new Matrix();
matrix.postScale(size.scale, size.scale);
BitmapFactory.Options scaledOpts = new BitmapFactory.Options();
scaledOpts.inSampleSize = size.sample;
scaled = BitmapFactory.decodeResource(resources, resId, scaledOpts);
}
private Size getRoughSize(InputStream is, int newWidth) {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, o);
Size size = getRoughSize(o.outWidth, o.outHeight, newWidth);
return size;
}
private Size getRoughSize(Resources resources, int resId, int newWidth) {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeResource(resources, resId, o);
Size size = getRoughSize(o.outWidth, o.outHeight, newWidth);
return size;
}
private Size getRoughSize(int outWidth, int outHeight, int newWidth) {
Size size = new Size();
size.scale = outWidth / newWidth;
size.sample = 1;
int width = outWidth;
int height = outHeight;
int newHeight = (int) (outHeight / size.scale);
while (true) {
if (width / 2 < newWidth || height / 2 < newHeight) {
break;
}
width /= 2;
height /= 2;
size.sample *= 2;
}
return size;
}
}
http://zerocredibility.wordpress.com/2011/01/27/android-bitmap-scaling/
if you are using PNG format then it will not compress your image because PNG is a lossless format. use JPEG for compressing your your image and use 0 instead of 100 in quality.
What's the problem exactly? Doesn't your code manage to open the file ? does it crash or have you just no error, but no output file?
By the way, you should call bitmap.recycle() at the end
It could help you harry
crop-image
BitmapFactory.Options optionsSignature = new BitmapFactory.Options();
final Bitmap bitmapSignature = BitmapFactory.decodeFile(
fileUriSignature.getPath(), optionsSignature);
Bitmap resizedSignature = Bitmap.createScaledBitmap(bitmapSignature, 256, 128, true);
signature.setImageBitmap(resizedSignature);
I have this project in which I have a bitmap bigger than the screen size. I want to resize it to fit the screen exactly. I have no titlebar, and I am in fullscreen mode. This is my non-working code:
public class ScopView extends View
{
private Scop thescop;
public ScopView(Context context, Scop newscop)
{
super(context);
this.thescop = newscop;
}
#Override
public void onDraw(Canvas canvas)
{
Bitmap scopeBitmap;
BitmapFactory.Options bfOptions = new BitmapFactory.Options();
bfOptions.inDither = false;
bfOptions.inPurgeable = true;
bfOptions.inInputShareable = true;
bfOptions.inTempStorage = new byte[32 * 1024];
scopeBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.scope, bfOptions);
scopeBitmap.createScaledBitmap(scopeBitmap, SniperActivity.Width, SniperActivity.Height, false);
canvas.drawBitmap(scopeBitmap, SniperActivity.scopx, SniperActivity.scopy, null);
}
}
While in here the createScaledBitmap method, I am using itself as the source, and some variables from an activity used to retrieve the window height and width from screen preferences.
You can use the below code to resize the bitmap.
int h = 320; // Height in pixels
int w = 480; // Width in pixels
Bitmap scaled = Bitmap.createScaledBitmap(largeBitmap, h, w, true);
Also, you can use the below code snippet.
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
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
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
This code is help to you try this
int REQ_WIDTH = 0;
int REQ_HEIGHT = 0;
REQ_WIDTH =imageView.getWidth();
vREQ_HEIGHT =imageView.getHeight();
mImageView.setImageBitmap(Bitmap.createScaledBitmap(BitmapFactory.decodeFile(imageURI, options), REQ_HEIGHT, REQ_WIDTH, true));
i am saving a captured image in sdcard by using following code
class SavePhotoTask extends AsyncTask<byte[], String, String> {
#Override
protected String doInBackground(byte[]... jpeg) {
File photo=new File(Environment.getExternalStorageDirectory(),"photo.jpg");
if (photo.exists()) {
photo.delete();
}
try {
FileOutputStream fos=new FileOutputStream(photo.getPath());
fos.write(jpeg[0]);
fos.close();
}
catch (java.io.IOException e) {
Log.e("PictureDemo", "Exception in photoCallback", e);
}
return(null);
}
}
but i am getting the image of resolution 1024*768 how can i change the resoultion of that image.
i am calling SavePhotoTask like this
Camera.PictureCallback photoCallback=new Camera.PictureCallback(){
public void onPictureTaken(byte[] data, Camera camera){
bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap mutableBitmap = bmp.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);
canvas.drawBitmap(itembmp,left,right,null);
image.setImageBitmap(mutableBitmap);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
mutableBitmap.compress(Bitmap.CompressFormat.PNG,100, stream);
byte[] byteArray = stream.toByteArray();
new SavePhotoTask().execute(byteArray);
Toast.makeText(PreviewDemo1.this,"Image Saved",Toast.LENGTH_LONG).show();
camera.startPreview();
inPreview=true;
}
};
thanks in advance
It is the jpeg passed to the doInBackground method that already has that resolution - you need to change whatever is calling this code.
If you can parse it to BitMap then you can use this:
private final int MAX_WIDTH = 400;
private final int MAX_HEIGHT = 400;
public Bitmap getResizedBitmap(Bitmap bm) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth;
float scaleHeight;
if (width < MAX_WIDTH && height < MAX_HEIGHT) {
return bm;
}
if (width > height) {
scaleWidth = ((float) MAX_WIDTH) / width;
scaleHeight = ((float) MAX_HEIGHT * height / width) / height;
} else {
scaleWidth = ((float) MAX_WIDTH * width / height) / width;
scaleHeight = ((float) MAX_HEIGHT) / height;
}
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
matrix, false);
return resizedBitmap;
}