Upload a Image in server in Android using URI in JSON webservices - android

I want to send a image to server in a JSON webservice (by using a string parameter in JSON post method) and i want to get image from URI path.

The folowing class is what i use to download a picture (in my case it was a jpeg) from a given url. It is a piece from my own code so there may be some project specific stuff in there. Just read past that:).
public class BitmapFromUrl
{
private Bitmap myBitmap;
public BitmapFromUrl(String imageUrl)
{
URL myImageURL = null;
try
{
myImageURL = new URL(imageUrl);
}
catch (MalformedURLException error)
{
Log.e("tag", "The URL could not be formed from the provided String" + error);
}
if((myImageURL != null) && (imageUrl != null)) {
try
{
HttpURLConnection connection = (HttpURLConnection)myImageURL .openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
myBitmap = BitmapFactory.decodeStream(input);
}
catch (IOException e)
{
Log.e("tag", "The Bitmap could not be downloaded or decoded!" + e);
}
} else {
Log.e("tag", "The provided URL(\"" + imageUrl + "\") does not seem to be valid.");
myBitmap = null;
}
}
public Bitmap getBitmap()
{
return myBitmap;
}
}
To send get a String of this image you can use the following:
Bitmap bm = BitmapFactory.decodeFile("/thePathToYour/image.jpeg");
ByteArrayOutputStream output = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, output); //bm is the bitmap object
byte[] bytes = output.toByteArray();
String base64Image = Base64.encode(bytes, Base64.DEFAULT);
Now you have the image as a string. On the server you can change it back to an image using the Base64 methods of your servers programming language.
json.put(WebConstant.JSON_PUT_PROPERTY_BUZZ_IMAGE, base64Image);
This should do the job.

in your line:
json.put(WebConstant.JSON_PUT_PROPERTY_BUZZ_IMAGE, " SEND IMAGE as URI ");//buzzInfoBean.getBuzzImage());
"SEND IMAGE as URI " should be a base64 encoded string most likely, I don't know what the server is expecting, but that is most common.
Check out the answer to this question
Getting the image from the local uri
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri1)

Related

Uploading Image from Android to Node

I am trying to upload multiple images to my node server via Android Studio. However the image file always seems to be corrupt on the server. I am able to take and preview the picture in Android but not able to store it on my server.
Here is my server code
app.post('/upload', function(req, res) {
var base64Data = req.rawBody;
fs.writeFile("test.jpg",base64Data,'base64',function(err,written){
if(err) console.log(err);
else {
console.log("file Succesfully written ");
cloudinary.uploader.upload("test.jpg", function (image) {
if(image !== undefined) {
res.json({link: image.secure_url}).end();
console.log("url = " , image.secure_url);
// fs.unlink(ImageFile);
} else console.log.error("Error uploading to Cloudinary, ", image);
});
}
});
});
Here is my front end code I use to convert my bitmap to an encoded Base64 String.
final String encodedString = ImageBase64.encode(fileArray.get(i));
Here is a log of what encodedString holds after being set. Obviously the full value is not displayed.
/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAMgA+gDASIA
AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA
However on my backend it is displayed as this
2F9j%2F4AAQSkZJRgABAQAAAQABAAD%2F2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB%0AAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH%2F2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB%0AAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH%2FwAARCAMgA%2BgDASIA%0AAhEBAxEB%2F8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQ
If you get it url encoded then you should url decode it.
InputStream imageStream;
try {
imageStream = getContentResolver().openInputStream(uri);//uri is the image URI
Bitmap bm = BitmapFactory.decodeStream(imageStream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] byteArray = baos.toByteArray();
String encodedImage = Base64.encodeToString(byteArray,Base64.NO_WRAP);//encodedImage is your image string
} catch (FileNotFoundException e) {
e.printStackTrace();
}

Encode facebook url image to BASE 64 string in android

Let me explain my problem.
I am trying to set Facebook profile image in app Imageview some thing like this ..
// Getting Facebook URL image and converting same to bitmap
Bitmap mIcon1;
URL img_value = new URL("http://graph.facebook.com/"+ userProfileID +"/picture?type=square");
BitmapFactory.Options options = new BitmapFactory.Options();
mIcon1 = BitmapFactory.decodeStream(img_value.openConnection().getInputStream(), null, options);
Then after ..
// I am setting bitmap to imageview .. some thing like ..
if(mIcon1!=null) {
user_picture.setImageBitmap(mIcon1);
}
Up to here it is working great ...
Now I need to save that Facebook Profile image into my DB located at server ...
I am performing that stuff some thing like ..
// Created a method for encoding ..
public static String encodeTobase64(Bitmap image)
{
Bitmap immagex=image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);
Log.e("LOOK", imageEncoded);
return imageEncoded;
}
// Now trying to use this method to get encoded BASE 64 image in string ..
String final_image = encodeTobase64(mIcon1);
Now when I try to send this string to my server then at server end I am recieving broken link ... Instead I must say that it's not working ..
I need to perform two of stuff
Encode Facebook profile image to Encoded BASE 64 string so as to send same to server.
Get type of image (i.e. PNG/ JPG ... ) or compress and send that image in one specific format.
Looking forward for any suggestion on this.
Thanks!
I got solution of this and hope this will help some one ..
# Base concept :-- We generally use GET or POST method while sending data to server.
1- GET:-- In this method you can only send specific amount of data ..
2- POST :-- In this method you can send huge amount of data ..
Problem was :-- Exact problem was that .. I was using GET method while sending data to server. Above mentioned concept was know to me . but, some how I did that mistake.
Solution :-- You simply need to send data to server using POST method instead of GET.
Complete solution for this in undermentioned :--
// Define your ASYNC TASK like ..
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
new ImageTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else{
new ImageTask().execute();
}
AND
// Now here comes your complete Async Task over here ..
private class ImageTask extends AsyncTask<Void, Integer, Void> {
Bitmap mIcon1;
#Override
protected Void doInBackground(Void... params) {
URL img_value = null;
Log.d("taking", "2");
try {
if(type_of_login.equalsIgnoreCase("facebook")){
img_value = new URL("http://graph.facebook.com/"+ user_id +"/picture?type=square");
System.out.println("Complete URl is:============================= " + img_value);
}else{
img_value = new URL("https://plus.google.com/s2/photos/profile/"+ user_id +"?sz=50");
System.out.println("Complete URl is:============================= " + img_value);
}
//img_value = new URL("http://graph.facebook.com/"+ userProfileID +"/picture?type=square");
BitmapFactory.Options options = new BitmapFactory.Options();
mIcon1 = BitmapFactory.decodeStream(img_value.openConnection().getInputStream(), null, options);
Log.d("taking", "3" + img_value);
Log.d("taking", "3" + mIcon1);
Log.d("taking", String.valueOf(mIcon1));
ByteArrayOutputStream bao = new ByteArrayOutputStream();
mIcon1.compress(Bitmap.CompressFormat.JPEG, 100, bao);
byte [] ba = bao.toByteArray();
encoded_image =Base64.encodeToString(ba,Base64.DEFAULT);
System.out.println("Encoded image is : ===== " + encoded_image);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if(mIcon1!=null)
{
user_pic.setImageBitmap(mIcon1);
get_string_image = encodeTobase64(mIcon1);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
}
}
}
Now finally our dream method ..
public static String encodeTobase64(Bitmap image)
{
Bitmap immagex=image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);
Log.e("LOOK", imageEncoded);
return imageEncoded;
}
Now when you need to send data over API then simply execute HttpPost instead of HttpGet
That's it .. you are good to go with this ..

how to read images form inpustream to android

i have 2 applications. One application act as server and it is created in java and sends continuously screen shot of desktop by using the following code.
public void screenCap() throws IOException, AWTException{
Rectangle captureSize = new Rectangle(lastXpos, lastYpos, 500, 500);
img = robot.createScreenCapture(captureSize);
Robot robot=new Robot();
OutputStream os = null;
BufferedImage image = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
ImageIO.write(image, "jpg", os);
}
The second application is Android application acts a client application and has to read continuously the above image stream from inputstream.
Could please help me to read the images from inputstream in the client application.
Use Bitmap decodeStream() method of BitmapFactory Class.
public static Bitmap decodeStream (InputStream is)
Since: API Level 1
Decode an input stream into a bitmap. If the input stream is null, or cannot be used to decode a bitmap, the function returns null. The stream's position will be where ever it was after the encoded data was read.
Example:
String urlOfBitmap = ""; // Url of inputstream
Bitmap bitmap = null;
try {
InputStream in = new java.net.URL(urlOfBitmap).openStream();
bitmap = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
FileInputStream in;
in = ...;
bitmap = BitmapFactory.decodeStream(in);

BitmapFactory returns null

I am working on an application where I am getting an image from the web server.
I need to save that image in a sqlite database. Maybe it will be saved in a byte[]; I have done this way, taking the datatype as blob, and then retrieving the image from db and showing at imageview.
I am stuck somewhere, however: I am getting null when I decodefrom bytearray
The code I have used is:
InputStream is = null;
try {
URL url = null;
url = new URL(http://....);
URLConnection ucon = null;
ucon = url.openConnection();
is = ucon.getInputStream();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer barb = new ByteArrayBuffer(128);
int current = 0;
try {
while ((current = bis.read()) != -1) {
barb.append((byte) current);
} catch (IOException e) {
e.printStackTrace();
}
byte[] imageData = barb.toByteArray();
Then I have inserted imageData in to the db..
To retrieve the image:
byte[] logo = c.getBlob(c.getColumnIndex("Logo_Image"));
Bitmap bitmap = BitmapFactory.decodeByteArray(logo, 0, logo.length);
img.setImageBitmap(bitmap);
But I am getting the error:
Bitmap bitmap is getting null.
Sometimes, It happens, when your byte[] not decode properly after retrieving from database as blob type.
So, You can do like this way, Encode - Decode,
Encode the image before writing to the database:
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.JPEG, THUMB_QUALITY, outputStream);
mByteArray = outputStream.toByteArray(); // write this to database as blob
And then decode it like the from Cursor:
ByteArrayInputStream inputStream = new ByteArrayInputStream(cursor.getBlob(columnIndex));
Bitmap mBitmap = BitmapFactory.decodeStream(inputStream);
Also, If this not work in your case, then I suggest you to go on feasible way..
Make a directory on external / internal storage for your application
images.
Now store images on that directory.
And store the path of those image files in your database. So you
don't have a problem on encoding-decoding of images.

Android : Getting this error while downloading image from remote server: SkImageDecoder::Factory returned null

I am trying to download images from a remote server, the number of images downloaded is 30. The code i am using to download image is as below. Some images download successfully and some images don't download and raises the above exception. What might be the problem.
public static Bitmap loadBitmap(String url)
{
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), 4*1024);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, 4 * 1024);
int byte_;
while ((byte_ = in.read()) != -1)
out.write(byte_);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e("","Could not load Bitmap from: " + url);
} finally {
try{
in.close();
out.close();
}catch( IOException e )
{
System.out.println(e);
}
}
return bitmap;
}
Please look on my this post
Image download code works for all image format, issues with PNG format rendering
In my case I solved this error with encode the url
Because image url that i wanted to download has the Persian letters(or other Unicode character) in it
So I replaced all Persian characters with encoded UTF-8 letters

Categories

Resources