I want to read binary file that is placed in server. what i want is data should be placed in bytearray.
Following is my piece of code:
BufferedReader in = new BufferedReader(new InputStreamReader(uurl.openStream()));
String str;
while ((str = in.readLine()) != null) {
text_file=text_file+str;
text_file=text_file+"\n";
}
m_byteVertexBuffer=text_file.getBytes();
But i am not getting correct result
Try this: (it reads an image, but could modified to read generic binaries)
aURL = new URL(imageUrl);
URLConnection conn = aURL.openConnection();
InputStream is = new BufferedInputStream(conn.getInputStream());
BitmapFactory.Options options = new BitmapFactory.Options();
is = new BufferedInputStream(conn.getInputStream());
bm = BitmapFactory.decodeStream(is, null, options);
is.close();
Related
I am developing an android application in which I use ImageView to capture an image using camera.
So how can I send the captured image in imageview to a java servlet as multipart using httppost.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageView view = (ImageView)findViewById(R.id.imageView1);
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bm = view.getDrawingCache();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
Thanks.
Take a look here: http://developer.android.com/reference/java/net/HttpURLConnection.html
Example code:
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
writeStream(out);
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
finally {
urlConnection.disconnect();
}
Please refer to section Posting Content.
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/
I am making a xml file and saving it on my device code follows
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xx:xx:xx:xx:yy/LoginAndroid.asmx/login");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
//Toast.makeText( getApplicationContext(),"responseBody: "+responseBody,Toast.LENGTH_SHORT).show();
//saving the file as a xml
FileOutputStream fOut = openFileOutput("loginData.xml",MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(responseBody);
osw.flush();
osw.close();
//reading the file as xml
FileInputStream fIn = openFileInput("loginData.xml");
InputStreamReader isr = new InputStreamReader(fIn);
char[] inputBuffer = new char[responseBody.length()];
isr.read(inputBuffer);
String readString = new String(inputBuffer);
FIle is saving I can also read the file every thing is ok but look at this line
char[] inputBuffer = new char[responseBody.length()];
it is calculating string length which is saved at the time of Saving the file.I am saving the file in one Acivity and reading it from another activity and my application will save the file locally once so I could not be able to get the length of that return string every time So is there any way to allocate the size of char[] inputBuffer dynamically?
you can use the below code in your another activity to read the file. Have a look at BufferedReader class.
InputStream instream = new FileInputStream("loginData.xml");
// if file the available for reading
if (instream != null) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
// read every line of the file into the line-variable, on line at the time
while (buffreader.hasNext()) {
line = buffreader.readLine();
// do something with the line
}
}
Edit:
The above code is working fine for reading a file, but if you just want to allocate the size of char[] inputBuffer dynamicall then you can use the below code.
InputStream is = mContext.openFileInput("loginData.xml");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
while ((int bytesRead = is.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byte[] inputBuffer = bos.toByteArray();
Now , make use inputBuffer as you want.
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
I am making an application in android which loads Icon size images from URL
i have tried downloading images using the following code.
One image labeled default.png was downloaded from the given url but there was another image labeled v_1234.jpg is not being downloaded. I dont know whats the problem. it just returns me null for jpg image.
I am not sure that its a problem for .jpg format that my code is not downloading the jpg format images or Its the labeled name problem that due to Underscore (_) in the label makes it not downloadable..
Please help Friends you are professional in that field.
CODE:
URL url = new URL(detail.voucher_image.toString());
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.getImageBitmap(bmp);
Thanks alot.
try this code
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
InputStream reader;
reader=conn.getInputStream();
System.out.println("Compressed2!!!"+conn.getContentLength());
int available = reader.available();
int i=0;
int count=0;
int cc=0;
while(reader.read()!=-1){
cc++;
}
System.out.println("available"+cc);
data2 = new byte[cc];
while ((i = reader.read(data2, count, data2.length-count)) != -1) {
count +=i;
cc++;
}
System.out.println("Compressed3!!!");
// reader.read(data2,0,cc);
System.out.println("Compressed!!!");
// printBytes(data1,data2,"after");
System.out.println("length b4!!!"+data2);
System.out.println("data::"+new String(data2));
System.out.println("The length is "+data2.length);
bmp2=BitmapFactory.decodeByteArray(data2, 0, data2.length);
if(bmp2==null)
System.out.println("The bitmap value is null");
iv.setImageBitmap(bmp2);undefined
use the following code to get bitmap from url
public Bitmap imageConvert(String url){
URL aURL = null;
Bitmap bm = null;
try {
final String imageUrl =imgstr.replaceAll(" ","%20");
Log.e("Image Url",imageUrl);
aURL = new URL(imageUrl);
URLConnection conn = aURL.openConnection();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(new PatchInputStream(is));
is.close();
}
catch (Exception e) {
Log.e("ProPic Exception",e.getMessage());
}
return bm;
}