how to read images form inpustream to android - 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);

Related

BitmapFactory cannot decode an image

In a React Native app for Android, I am trying to write an image (passed as base64) onto the filesystem and later decode it using BitmapFactory.
Why is BitmapFactory still unable to decode the image after using (Base64.decode) while storing it?
The error:
Cannot decode bitmap:
file:///data/data/com.reactnativeapp/files/rct-image-store/1
The custom written method storing the image:
#ReactMethod
public void addImageFromBase64(String base64_image_data, Callback successCallback, Callback failureCallback){
String imageStorageDir = this.reactContext.getApplicationContext().getFilesDir()+"/rct-image-store/";
String file_uri = imageStorageDir+"1";
try {
File f = new File(imageStorageDir);
if(!f.exists()) {
f.mkdir();
}
FileOutputStream fos = new FileOutputStream(file_uri, false);
byte[] decodedImage = Base64.decode(base64_image_data, Base64.DEFAULT);
fos.write(decodedImage);
fos.close();
successCallback.invoke("file://"+file_uri);
} catch (IOException ioe) {
failureCallback.invoke("Failed to add image from base64String"+ioe.getMessage());
} catch (Exception e) {
failureCallback.invoke("Failed to add image from base64String"+e.getMessage());
}
}
Shortened method for accessing the image (fullResolutionBitmap is null):
InputStream inputStream = mContext.getContentResolver().openInputStream(Uri.parse(uri));;
BitmapFactory.Options outOptions = new BitmapFactory.Options();
Bitmap fullResolutionBitmap = BitmapFactory.decodeStream(inputStream, null, outOptions);/// fullResolutionBitmap==null
Here is the image, the bottom part looks cropped. Since both original and converted image have the grey area, the problem seems to be not with the conversion of the image, but with the source (camera).
Original image:
Converted image:

Creating an Android Bitmap from an Amazon S3 object with BitmapFactory?

I have an image in the S3 server stored with the .bmp extension and retrieve the object with a call to getObject(). I then instantiate an InputStream with a call to getObjectContent(). I'm trying to create a bitmap object by passing the inputStream to BitmapFactory's decodeStream() method. As stated in the docs, it is returning null (instead of a Bitmap) presumably because the inputStream "cannot be used to decode a bitmap". Any ideas on why this is happening? Alternatively, ideas on other ways to download a photo from S3 would be greatly appreciated. Thanks so much!
GetObjectRequest getPhoto = new GetObjectRequest(MainActivity.USERS_BUCKET_NAME, finalList.get(i));
S3Object photoObject = s3.getObject(getPhoto);
InputStream inputStream = photoObject.getObjectContent();
//process inputStream
Bitmap bmp = BitmapFactory.decodeStream(inputStream); //this is returning null
//close inputStream
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
I fixed the problem by using the Apache Commons IOUtils library - I converted the inputstream into a byte array with IOUtils.toByteArray(inputStream) and passed that into BitmapFactory.decodeByteArray(); it no longer returns null.

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.

How can I convert response json string image into a displayable image

My final year project requires me to develop a mobile application which fetches a number of Json values from a server. This is my first experience in android development but sure learned something’s and enjoyed the experience.
I have managed to develop the following.
1-a json parser class which fetches the value.
2-a class which displays these values.
3-a database where I store the json response.
However I'm one step away from completing my project, I cannot display the response string image address as real images (shame on me).
I need to do the following.
1- Parse the string path of the image and display the response as image.
I have spent most of my time trying to find the solution on the web, stack overflow. But no luck so far.
I need to do something like this in order to display these images together with the text descriptions.
I have now reached the cross roads and my knowledge has been tested.Is what i'm trying to do here posible?.
Who can show me the way? ,to this outstanding platform.
if you have the image url as a string, you can load and save the image using something like this:
try {
Bitmap bitmap = null;
File f = new File(filename);
InputStream inputStream = new URL(url).openStream();
OutputStream outputStream = new FileOutputStream(f);
int readlen;
byte[] buf = new byte[1024];
while ((readlen = inputStream.read(buf)) > 0)
outputStream.write(buf, 0, readlen);
outputStream.close();
inputStream.close();
bitmap = BitmapFactory.decodeFile(filename);
return bitmap;
} catch (Exception e) {
return null;
}
For saving, make sure you have appropriate permissions if you're going to save to sdcard.
if you just want to load the image (without saving):
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e(TAG, "Error getting bitmap", e);
}
return bm;
Just make sure you fetch the image in a separate thread or using AsyncTask or else you'll get ANRs!
you can try this ImageDownloader class from google. It´s works nice :)
Is an AsynkTask that handle the download and set the bitmap to an ImageView.
ImageDownloader
Usage:
private final ImageDownloader mDownload = new ImageDownloader();
mDownload.download("URL", imageView);

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