why image blur after upload android? - android

I am learning Upload image to server where image taked from gallery or camera android ....
When i show image after take from gallery or camera to imageview with image decode, image not blur...
but after i upload, image like be small size and blurred ..
I do not know, where is the mistake. whether on the decoded image or upload image
here part of my code
decode code
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);
imgView.setImageBitmap(bitmap);
}
upload code
try {
DatabaseHandler userDB = new DatabaseHandler(getApplicationContext());
HashMap<String, String> userDetail = userDB.getUserDetails();
String uid= userDetail.get("uid");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(PHP_URL);
ByteArrayBody bab = new ByteArrayBody(data,file_name);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("uploadedfile", bab);
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),"UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
return s.toString().trim();
} catch (Exception e) {
err="error"+e.getMessage();
Log.e(e.getClass().getName(), e.getMessage());
return e.getMessage();
}
before upload, image show in ImageView
After upload, and show in listview
I hope anyone can help me. Sorry if my English is not good ...

According to method documentation you are compressing image 100 percent which degrades the quality
bitmap.compress(CompressFormat.JPEG, 100, bos);
i suggest using a smaller value than 100 and adjusting till you get a balance between quality and size

Related

How to prevent out of memory exception while trying to convert input stream object into bitmap in android?

I had used following code to convert inputstream object into bitmap. But it returns "out of memory error", and BitmapFactory Options always returns Zero.
S3ObjectInputStream inputStreamReceiptObject = objectReceiptFromAmazonS3
.getObjectContent();
Bitmap bitmapImageFromAmazon = null;
try {
if (inputStreamReceiptObject != null){
BitmapFactory.Options o = new BitmapFactory.Options();
o.inSampleSize = 8;
o.inJustDecodeBounds = true;
bitmapImageFromAmazon = BitmapFactory.decodeStream(inputStreamReceiptObject,null,o); // o is always null
if(bitmapImageFromAmazon == null){
System.out.println("Bitmap null");
}
}
Advance Thanks for any help !
SOLUTION : ( Lot of thanks to Honourable Don and Honourable Akshat )
ByteArrayOutputStream baos = null ;
InputStream is1 = null,is2 = null;
try {
baos = new ByteArrayOutputStream();
// Fake code simulating the copy
// You can generally do better with nio if you need...
// And please, unlike me, do something about the Exceptions :D
byte[] buffer = new byte[1024];
int len;
while ((len = inputStreamReceiptObject.read(buffer)) > -1 ) {
baos.write(buffer, 0, len);
}
baos.flush();
// Open new InputStreams using the recorded bytes
// Can be repeated as many times as you wish
is1 = new ByteArrayInputStream(baos.toByteArray());
is2 = new ByteArrayInputStream(baos.toByteArray());
bitmapImageFromAmazon = getBitmapFromInputStream(is1,is2);
if(bitmapImageFromAmazon == null)
System.out.println("IMAGE NULL");
else
System.out.println("IMAGE NOT NULL");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
baos.close();
is1.close();
is2.close();
}
public Bitmap getBitmapFromInputStream(InputStream is1,InputStream is2) throws IOException {
Bitmap bitmap = null;
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is1,null,o);
//Find the correct scale value. It should be the power of 2.
int scale=1;
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
bitmap = BitmapFactory.decodeStream(is2, null, o2);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
Why dont you try and scale the bitmap image down? Thats mostly the reason why your app showed OOM exception
BitmapFactory.Options o = new BitmapFactory.Options();
o.inScaled = false;
o.inJustDecodeBounds = true;
FileInputStream stream1 = new FileInputStream(f);
BitmapFactory.decodeStream(stream1, null, o);
stream1.close();
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70; //This is the max size of the bitmap in kilobytes
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
FileInputStream stream2 = new FileInputStream(f);
Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
return bitmap;
The Out Of Memory error should be as it says: you do not have enough memory on your device to render the entire image. You need to ensure that the image you're downloading from S3 is not too big for the device.
To help you debug, try running downloading a smaller image to see if you are still receiving the OOM errors
URLConnection conn = new URL("http://upload.wikimedia.org/wikipedia/commons/thumb/a/a1/Victoria_Parade_postcard.jpg/120px-Victoria_Parade_postcard.jpg").openConnection();
InputStream stream = conn.getInputStream();
Bitmap image = BitmapFactory.decodeStream(stream, null, null);
The o you pass into decodeStream is null because of the OOM error (it must have gone out of scope when you examined it in the debugger).

How to receive a byte array and convert it to image in Android?

I have used:
InputStream in;
Bitmap bmp=BitmapFactory.decodeStream(in);
but the process waits for a long time and nothing happens. On the server side, i have the image converted into byte[].
I think this piece of code will be useful for you:
public Bitmap DownloadImage(String url)
{
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
Bitmap bmp = null;
try{
httpResponse = client.execute(new HttpGet(url));
responseCode = httpResponse.getStatusLine().getStatusCode();
HttpEntity entity = httpResponse.getEntity();
if (entity != null)
{
InputStream in = entity.getContent();
bmp = BitmapFactory.decodeStream(in);
in.close();
}
} catch (ClientProtocolException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
} catch (IOException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
}
return bmp;
}
Try this way to convert to bitmap.
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();
InputStream is;
OutputStream os = new FileOutputStream(f);
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}

java.lang.outofmemoryerror bitmap size exceeds vm budget on bitmap

In my app I'm displaying images from galley and on selection of image i want to upload that image to web server.For uploading image to server I'm using following code but I'm getting error at
bitmapImage = BitmapFactory.decodeFile(path,opt);
private void uploadImage(String selectedImagePath) {
String str = null;
byte[] data = null;
String Responce= null;
Bitmap bitmap2 = null;
try {
File file=new File(selectedImagePath);
//FileInputStream fileInputStream = new FileInputStream(new File(imagePath2) );
FileInputStream fileInputStream=new FileInputStream(selectedImagePath);
Log.i("Image path 2",""+selectedImagePath+"\n"+fileInputStream);
name=file.getName();
name=name.replace(".jpg","");
name=name.concat(sDate).concat(".jpg");
Log.e("debug",""+name);
//else
//{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inTempStorage = new byte[16*1024];
//bitmapImage = BitmapFactory.decodeFile(path,opt);
bitmap2=BitmapFactory.decodeFileDescriptor(fd, outPadding, opts)
Log.i("Bitmap",""+bitmap.toString());
BitmapFactory.decodeStream(fileInputStream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap2.compress(Bitmap.CompressFormat.PNG, 100, baos);
data = baos.toByteArray();
str=Base64.encodeBytes(data);
//}
//String image=str.concat(sDate);
ArrayList<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",str));
nameValuePairs.add(new BasicNameValuePair("imagename", name));
Log.e("debug",""+nameValuePairs.toString());
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost("http://ufindfish.b4live.com/uploadTipImage.php");
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse=client.execute(post);
HttpEntity entity=httpResponse.getEntity();
InputStream inputStream=entity.getContent();
StringBuffer builder=new StringBuffer();
int ch;
while( ( ch = inputStream.read() ) != -1 )
{
builder.append((char)ch);
}
String s=builder.toString();
Log.i("Response",""+s);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(bitmap2!=null)
{
bitmap2.recycle();
}
Error is due to the size of the image, i used this code to decrease the size of image when select from gallery.
public Bitmap setImageToImageView(String filePath)
{
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true)
{
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap bitmap = BitmapFactory.decodeFile(filePath, o2);
return bitmap;
}
i hope this may helps you.
You have to break in to samples while loading the image, there is already a question and a good answer for it, have a look at this page , this might help you.
Strange out of memory issue while loading an image to a Bitmap object

image from url to drawable or bitmap :best and fastest way

im tried to show images from url in my app. But ways which im using is very long .
this code i founded on stackoverflow
public Bitmap getImage(String url,String src_name) throws java.net.MalformedURLException, java.io.IOException {
Bitmap bitmap;
HttpURLConnection connection = (HttpURLConnection)new URL(url) .openConnection();
connection.setRequestProperty("User-agent","Mozilla/4.0");
connection.connect();
InputStream input= connection.getInputStream();
bitmap = BitmapFactory.decodeStream(input);
return bitmap;
}
10 images loaded in 10-12 second. if used this code.
and
///==========================================================================================================================================
public Drawable getImage(String url, String src_name) throws java.net.MalformedURLException, java.io.IOException
{
Drawable abc =Drawable.createFromStream(((java.io.InputStream)new java.net.URL(url).getContent()), src_name);
return abc;
}
if using this code - images loaded in 9-11 seconds.
Images not big . max width or height is 400-450.
ofcourse i tell this function in cycle like this : for (int i =0;i<10;i++){image[i]=getImage(url);}
Can any tell how to best and faste show image in my app ?
regards, Peter.
You cannot do away with the time required for downloading and decoding images. The number '10' is just a function on the quality of the image and you can only try to optimize on this number.
If the server is managed by you, you might want to spend some time optimizing on the size of the downloadable images given your UI requirements. Also try lazy-loading (I hope you are not performing these operations on the UI thread). Many solutions for lazy-downloading and lazy-decoding have been discussed many times: http://www.google.com.sg/search?q=android+images+lazy+load&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a
Sidenote: The usage of HttpURLConnection is discouraged. Use the HttpClient. This might also affect performance. Take a look at http://lukencode.com/2010/04/27/calling-web-services-in-android-using-httpclient/
public static Bitmap getBitmapFromUrl(String url) {
Bitmap bitmap = null;
HttpGet httpRequest = null;
httpRequest = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = null;
try {
response = (HttpResponse) httpclient.execute(httpRequest);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (response != null) {
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = null;
try {
bufHttpEntity = new BufferedHttpEntity(entity);
} catch (IOException e) {
e.printStackTrace();
}
InputStream instream = null;
try {
instream = bufHttpEntity.getContent();
} catch (IOException e) {
e.printStackTrace();
}
bitmap = BitmapFactory.decodeStream(instream);
}
return bitmap;
}
public static Bitmap decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap bitmap = BitmapFactory.decodeFile(filePath, o2);
return bitmap;
}

BitmapFactory.decodeStream returns null without exception

I try to load a remote image from a server and thanks to a lot of code examples on stackoverflow I have a solution which works in 2 out of 3 images. I don't really know what the problem is with the third picture and sometimes when letting the code run in the debugger the picture is loading. Also if I load the problem picture first the other two pictures are sometimes not loaded.
Here is the code:
public static Drawable getPictureFromURL(Context ctx, String url, final int REQUIRED_SIZE) throws NullPointerException {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
int scale = 1;
if (o.outWidth > REQUIRED_SIZE) {
scale = (int) Math.pow(2, (int) Math.round(Math.log(REQUIRED_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
Log.i(Prototype.TAG, "scale: "+scale);
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap bmp;
try {
bmp = BitmapFactory.decodeStream((InputStream) Tools.fetch(url), null, o2);
if(bmp!=null)
return new BitmapDrawable(ctx.getResources(), bmp);
else
return null;
} catch (Exception e) {
Log.e(Prototype.TAG, "Exception while decoding stream", e);
return null;
}
}
During debugging I found out that o.outWidth is -1 which indicates an error, but no Exception is thrown, so I can't really tell what went wrong. The InputStream always returned a valid value, and I know that the picture exists on the server.
Best wishes,
Daniel
I found the answer here and updated the fetch method to:
private static InputStream fetch(String address) throws MalformedURLException,IOException {
HttpGet httpRequest = new HttpGet(URI.create(address) );
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
InputStream instream = bufHttpEntity.getContent();
return instream;
}

Categories

Resources