android send image to servlet using the imageview and HttpPost - android

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.

Related

Android: load images with zoom from URL

I am using to load my images with high resolution and zoom quality with the tutorial: https://github.com/davemorrissey/subsampling-scale-image-view
It uses images from Assets. How I could do to load images from a URL?
The class SubsamplingScaleImageView has also a method to load an image that isn't from Assets:
SubsamplingScaleImageView.setImageFile(String extFile)
So you can get the image from the URL and save it on internal storage. Then you can load the image using the path from internal storage.
To get the image as a Bitmap from an URL:
URL myFileUrl = new URL (StringURL);
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
Bitmap bm = BitmapFactory.decodeStream(is);
To save the Bitmap on internal storage:
FileOutputStream out = new FileOutputStream(context.getCacheDir() + filename);
bm.compress(Bitmap.CompressFormat.PNG, 90, out);
// Don't forget to add a finally clause to close the stream
Finally
SubsamplingScaleImageView imageView = (SubsamplingScaleImageView)findViewById(R.id.imageView);
imageView.setImageFile(context.getCacheDir() + filename);
I actually solved this by creating a Bitmap from the provided URL string extra, although I think this may defeat the purpose of SubsamplingScaleImageView because I'm loading the entire Bitmap.
private void locateImageView() throws URISyntaxException, IOException {
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
if (bundle.getString("imageUrl") != null) {
String imageUrl = bundle.getString("imageUrl");
Log.w(getClass().toString(), imageUrl);
imageView = (SubsamplingScaleImageView) findViewById(R.id.image);
URL newUrl = new URL(imageUrl);
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
imageView.setImage(ImageSource.bitmap(myBitmap));
} catch (IOException e) {
// Log exception
Log.w(getClass().toString(), e);
}
}
}
}

Android with plus sign ("+") in url

I cannot download the picture:
http://www.wallpick.com/wp-content/uploads/2014/02/08/Water+Sports_wallpapers_242-640x480.jpg
This is my code:
// from web
try {
Bitmap bitmap = null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setConnectTimeout(25000);
conn.setReadTimeout(25000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
// save file to m_FileCache
copyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex) {
return null;
}
With this code, I can download all image urls as:
http://www.wallpick.com/wp-content/uploads/2014/02/08/pictures-of-lotus-flowers-on-water-640x480.jpg
Root cause is plus sign ("+") in first link. Please help me! Thank you very much!
You can use Uri builder classes. As an example,
String url = Uri.parse("http://www.wallpick.com/wp-content/uploads/2014/02/08/").buildUpon()
.appendEncodedPath("Water+Sports_wallpapers_242-640x480.jpg")
.build().toString();
This will correctly encode your url String.

Bitmap decode stream from URL return nulled (SkImageDecoder::Factory returned null)

We try to decode image stream to Bitmap but it return nulled.
from this Code
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, options);
options.inSampleSize = calculateInSampleSize(options, 768, 1280);
options.inJustDecodeBounds = false;
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bm = BitmapFactory.decodeStream(bis, options);
bis.close();
is.close();
We get Log cat
SkImageDecoder::Factory returned null
but when we using only
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bm = BitmapFactory.decodeStream(bis);
it's work correctly.
I had an issue similar to this recently. There is an issue when decoding a InputStream in two passes (first for the image bounds, then the actual decoding), where the InputStream isn't reset after the first pass - which was causing the error in my case. To fix this, I just reset the InputStream after the first pass by closing the original stream that was used to get the image bounds, then reopening a new stream before doing the actual Bitmap decoding.
This fixed the problem in my situation, but this is a fairly common issue. If doing the above doesn't work - it might be worth looking into this Google Code issue, or this SO post about using BufferedHttpEntities.
I try to add below code before set inJustDecodeBounds to FALSE
//... calculateInSampleSize
is.close();
conn = aURL.openConnection();
conn.connect();
is = conn.getInputStream();
options.inJustDecodeBounds = false;
It's work correctly but I'm not sure this is bestway to solve my problem

How to read binary file place in server?

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();

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