Android - skia decode error for images - android

I have been trying to decode an image as follows:
String dat = jobJect.getString("dat");
client = new DefaultHttpClient();
String url2 = url1 + dat;
request = new HttpGet(url2);
request.setHeader("Cookie", "hcsid=" + GlobalConfig.hcSid);
response = client.execute(request);
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(
response.getEntity());
InputStream im = bufHttpEntity.getContent();
OutputStream out = null;
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
CameraActivity.copy(im, out);
out.flush();
final byte[] data = dataStream.toByteArray();
mBitMap = BitmapFactory.decodeByteArray(data, 0, data.length);
Although I get an image, it doesn't get decoded and throws this error:
09-29 11:27:38.675: DEBUG/skia(14907): --- decoder->decode returned false
I'm following this code which handles a skia error:
http://code.google.com/p/shelves/source/browse/trunk/Shelves/src/org/curiouscreature/android/shelves/util/ImageUtilities.java
But it doesn't solve the issue.
Can anyone please help?

Check this bug report:
http://code.google.com/p/android/issues/detail?id=9064

Related

Sending Multipart/Form request with multiple parameters?

I am trying to upload a picture to a server and i am getting different responses from the server depending upon the entity that i am sending.
When i send
FileBody fb = new FileBody(new File(filePath), "image/jpeg");
StringBody contentString = new StringBody(directoryID + "");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("file", fb);
entity.addPart("directory_id", contentString);
postRequest.setEntity(entity);
HttpResponse response = httpClient.execute(postRequest);
// Read the response
String jsonString = EntityUtils.toString(response.getEntity());
The response i get is {"status":"Success","code":"200","message":"File has been uploaded Successfully"}
if i send the same file in this way
Bitmap bitmapOrg = BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] data = bao.toByteArray();
StringBody contentString = new StringBody(directoryID + "");
ByteArrayBody ba = new ByteArrayBody(data, "image/jpeg", "file");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("file", ba);
entity.addPart("directory_id", contentString);
postRequest.setEntity(entity);
HttpResponse response = httpClient.execute(postRequest);
// Read the response
String jsonString = EntityUtils.toString(response.getEntity());
The response that i get now is {"status":"Failure","code":"501","message":"Invalid File to upload"}
So i was wondering Why is there difference between the two responses
?
Am i sending the post request parameter the right way ?
What do i have to do to post video in the same way ?
Below is the complete code for reference
public void uploadFile(int directoryID, String filePath) {
Bitmap bitmapOrg = BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
String upload_url = BASE_URL + UPLOAD_FILE;
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] data = bao.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(upload_url);
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
try {
// Set Data and Content-type header for the image
FileBody fb = new FileBody(new File(filePath), "image/jpeg");
ByteArrayBody ba = new ByteArrayBody(data, "image/jpeg", "file");
StringBody contentString = new StringBody(directoryID + "");
// If i do this
entity.addPart("file", fb);
// I get a valid response
// If i do this
entity.addPart("file", ba);
// I get an invalid response
entity.addPart("directory_id", contentString);
postRequest.setEntity(entity);
HttpResponse response = httpClient.execute(postRequest);
// Read the response
String jsonString = EntityUtils.toString(response.getEntity());
Log.e("response after uploading file ", jsonString);
} catch (Exception e) {
Log.e("Error in uploadFile", e.getMessage());
}
}
I was able to solve this problem so i am posting this answer because it might help others facing the same issue.
The problem was that the server to which i was uploading the picture file only parsed files having extensions JPEG, PNG, GIF etc and it ignored the rest of the files.
The image file that i was sending in the form of ByteArrayBody had the filename attribute without extension which as a result lead to this problem.
ByteArrayBody ba = new ByteArrayBody(data, "image/jpeg", "file");
entity.addPart("file", ba);
I replaced it with
ByteArrayBody ba = new ByteArrayBody(data, "image/jpeg", "file.jpeg");
entity.addPart("file", ba);
and it worked.

How to convert a picture before sending to the server?

in my current app I am sending pictures to my server. Now I have the problem that these pictures are sometimes too big. What is the best approach to downsize a picture before sending it to the server. Currently I stored the URI of the picture in a database (/mnt/sdcard/DCIM/SF.png) and send it to the server. I want to shrink the resolution of the image so that it will need a smaller amount of diskpace. Is there a way to convert images in android?
Can someone help me how to solve this in a good way?
Thanks
i used the following code to send the image to server, here i convert the image to byte array. Here first you need to decode the image from URI then convert the bitmap to byte array.
To decode bitmap from URI:
Bitmap imageToSend= decodeBitmap("Your URI");
Method to decode the URI
Bitmap getPreview(URI uri) {
File image = new File(uri);
BitmapFactory.Options bounds = new BitmapFactory.Options();
bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(image.getPath(), bounds);
if ((bounds.outWidth == -1) || (bounds.outHeight == -1))
return null;
int originalSize = (bounds.outHeight > bounds.outWidth) ? bounds.outHeight
: bounds.outWidth;
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = originalSize / THUMBNAIL_SIZE;
return BitmapFactory.decodeFile(image.getPath(), opts);
}
Code to send the image to server
try {
ByteArrayOutputStream bosRight = new ByteArrayOutputStream();
imageToSend.compress(CompressFormat.JPEG, 100, bosRight);
byte[] dataRight = bosRight.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("url to send");
ByteArrayBody babRight = new ByteArrayBody(dataRight,
"ImageName.jpg");
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("params", babRight);
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);
Log.v("Response value is", sResponse);
JSONObject postObj = new JSONObject(sResponse);
String successTag = postObj.getString("success");
if (successTag.equals("1")) {
imageDeletion();
} else {
}
}
} catch (Exception e) {
Log.e(e.getClass().getName(), e.getMessage());
}
for sending the image to a server you can encode it in Base64 and then send the Base64 encoded string to the server...
the base64 class in android doesn't support encoding so you will have to download the Bae64 java class file... You get it here http://iharder.sourceforge.net/current/java/base64/
after that its very simple.For example
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.YOURIMAGE);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String encodedstring=Base64.encodeBytes(ba);
Then send the encoded string as a normal name value pair
and a good example is given in this link http://blog.sptechnolab.com/2011/03/09/android/android-upload-image-to-server/

Android Image resize (resample/downsample) before uploading

private void doFileUpload(){
File file1 = new File(selectedPath1);
String urlString = "http://example.com/upload_media_test.php";
try
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
FileBody bin1 = new FileBody(file1);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("uploadedfile1", bin1);
reqEntity.addPart("user", new StringBody("User"));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
final String response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
Log.i("RESPONSE",response_str);
runOnUiThread(new Runnable(){
public void run() {
try {
res.setTextColor(Color.GREEN);
res.setText("n Response from server : n " + response_str);
Toast.makeText(getApplicationContext(),"Upload Complete. Check the server uploads directory.", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
catch (Exception ex){
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
}
I get this code from internet. it's work but when I try upload bigger file than 1Mbyte,
I face an error with filesize.
I know how to resize bitmap images and but I have no idea upload the resized bitmap image.
how can I resize and upload with filebody?
Thanks in advance
You need to not only resize the Bitmap, but you also need to encode the result as a .jpg image. Therefore, you must open the file and convert it to a Bitmap, resize the Bitmap to a smaller image, encode the image into a byte[] array, and then upload the byte[] array in the same manner as you have uploaded your file file1.
If the Bitmap is large, which it clearly is, you won't have enough heap memory to open the entire thing, so you will have to open it with BitmapFactory.Options.inSampleSize.
First, open the reduced size Bitmap:
Uri uri = getImageUri(selectedPath1);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4; // Example, there are also ways to calculate an optimal value.
InputStream in = in = contentResolver.openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(in, null, options);
Next, encode into a byte[] array:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
byte[] bitmapdata = bos.toByteArray();
Finally, use reqEntity.addPart() to add the byte[] array directly, or write to a smaller file and add the file as in your current example.
This answer is based on another answer, but I had some problems with that code, so I post the edited and working code.
I did it like this:
BitmapFactory.Options options = new BitmapFactory.Options();
options.outWidth = 50; //pixels
options.outHeight = 50; //pixels
InputStream in = context.getContentResolver().openInputStream(data.getData()); // here, you need to get your context.
Bitmap bitmap = BitmapFactory.decodeStream(in, null, options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] bitmapdata = baos.toByteArray();
Notice that, data is the returned data from the Intent you use to get the file. If you already have the file path, just use that...
And now, when you are creating the HTTP Entity, add:
FormBodyPart fbp = new FormBodyPart("image", new ByteArrayBody(baos.toByteArray(), "image/jpeg", "image"));
entity.addPart(fbp);
Also, notice that you need a MultipartEntity to upload files.

Image upload from android app

In my application I'm uploading an image on to the server. Here in the below code I'm uploading an image from the drawable folder.
But how can I upload an image from an imageview from the layout xml?
similarly like findviewbyid.imgid
My layout name is main.xml and image id is imgid
kindly help me...
Bitmap bitmap =
BitmapFactory.decodeResource(getResources(),R.drawable.avatar);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
byte [] byte_arr = stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",image_str));
We can upload image using Base64 string and multipart entity
for base64 string
ByteArrayOutputStream baos = new ByteArrayOutputStream();
btMap.compress(Bitmap.CompressFormat.JPEG, 100, baos); // bm is the
byte[] b = baos.toByteArray();
base64String = Base64.encodeBytes(b);
and for multipart
HttpPost httppost = new HttpPost("http://localhost:8080/upload.php");
File file = new File(yourimagepath);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();

Dynamically conversion of image to binary and vice versa

How can I convert image to binary data..???
I want to send that converted binary data to
another device or to the web server.
Which mechanism is best to do this.?
Image is in Bitmap then use the following code to convert that image to binary. By using following code
Bitmap photo;// this is your image.
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
To get Image From Binary use the following sample:
Bitmap bMap = null;
bMap = BitmapFactory.decodeByteArray(byteArray,0,byteArray.length);
I found a good example for uploading the image to the server.
create a bitmap variable before do anything.
variable to set a name to the image into SD card.
this variable, you have to put the path for the File, It's up to you.
sendData is the function name, to call it, you can use something like
sendData(null).
remember to wrap it into a try catch.
private Bitmap bitmap;
public static String exsistingFileName = "";
public void sendData(String[] args) throws Exception {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
// here, change it to your php;
HttpPost httpPost = new HttpPost("http://www.myURL.com/myPHP.php");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
bitmap = BitmapFactory.decodeFile(exsistingFileName);
// you can change the format of you image compressed for what do you want;
// now it is set up to 640 x 480;
Bitmap bmpCompressed = Bitmap.createScaledBitmap(bitmap, 640, 480, true);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// CompressFormat set up to JPG, you can change to PNG or whatever you want;
bmpCompressed.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
// sending a String param;
entity.addPart("myParam", new StringBody("my value"));
// sending a Image;
// note here, that you can send more than one image, just add another param, same rule to the String;
entity.addPart("myImage", new ByteArrayBody(data, "temp.jpg"));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
BufferedReader reader = new BufferedReader(new InputStreamReader( response.getEntity().getContent(), "UTF-8"));
String sResponse = reader.readLine();
} catch (Exception e) {
Log.v("myApp", "Some error came up");
}
}
Try this
Let img contains Bitmap image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "png", baos);
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
imageInByte now contains bytedata of bitmap image.
For converting reverse
Bitmap bp = BitmapFactory.decodeByteArray(imgArray, 0,imgArray.length);
Hope this may help you
if you want to send to webserver use HttpPost request using HttpClient

Categories

Resources