I would like to display an image from the URL that is providing me raw data for the image(png or JPG).
I checked this link but not much useful.
Here is my image link
I am processing the raw data but could not see the image. I am not sure how do I check that I got the right raw data.
here is my effort
private class DownloadImageTask extends AsyncTask<String, Void, Void> {
byte[] bytes;
Bitmap picture = null;
#Override
protected Void doInBackground(String... urls) {
// final OkHttpClient client = new OkHttpClient();
//
// Request request = new Request.Builder()
// .url(urls[0])
// .build();
//
// Response response = null;
//
// try {
// response = client.newCall(request).execute();
// } catch (IOException e) {
// e.printStackTrace();
// }
// assert response != null;
// if (response.isSuccessful()) {
// try {
// assert response.body() != null;
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// IOUtils.copy(response.body().byteStream(), baos);
// bytes = baos.toByteArray();
// picture = BitmapFactory.decodeStream(response.body().byteStream());
// } catch (Exception e) {
// Log.e("Error", Objects.requireNonNull(e.getMessage()));
// e.printStackTrace();
// }
//
// }
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
URL url = new URL(urls[0]);
byte[] chunk = new byte[4096];
int bytesRead;
InputStream stream = url.openStream();
while ((bytesRead = stream.read(chunk)) > 0) {
outputStream.write(chunk, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
bytes = outputStream.toByteArray();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (bytes != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
cameraView.setImageBitmap(bitmap);
}
// cameraView.setImageBitmap(picture);
}
}
The location of your problem/s in your workflow seems ill-determined.
You should first identify this.
(Plus, you did not specify if you are bound to a specific programming language).
For this sake, I suggest you:
Start using a raw image file that you know is correct, and test its processing.
There are quite a few raw image formats.
Judging from the tag android, I guess the following can help:
To capture a raw iamge into a file: How to capture raw image from android camera
To display in ImageView: Can't load image from raw to imageview
https://gamedev.stackexchange.com/questions/14046/how-can-i-convert-an-image-from-raw-data-in-android-without-any-munging
https://developer.android.com/reference/android/graphics/ImageFormat
https://www.androidcentral.com/raw-images-and-android-everything-you-need-know
Try getting a raw image from an URL that you can manage.
Apply this to the actual target URL.
This way you will know where your problem resides.
Without more info it is hard to "debug" your problem.
You can also inspect code in FOSS projects.
You could use a library named Picasso and do the following:
String url = get url from the Async Function and convert it to String
/*if you url has no image format, you could do something like this con convert the uri into a Bitmap*/
public Bitmap getCorrectlyOrientedImage(Context context, Uri uri, int maxWidth)throws IOException {
InputStream input = context.getContentResolver().openInputStream(uri);
BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
onlyBoundsOptions.inJustDecodeBounds = true;
onlyBoundsOptions.inDither = true;//optional
onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
try {
input.close();
} catch (NullPointerException e) {
e.printStackTrace();
}
/*trying to get the right orientation*/
if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1)) {
return null;
}
int originalSize = Math.max(onlyBoundsOptions.outHeight, onlyBoundsOptions.outWidth);
double ratio = (originalSize > maxWidth) ? (originalSize / maxWidth) : 1.0;
Matrix matrix = new Matrix();
int rotationInDegrees = exifToDegrees(orientation);
if (orientation != 0) matrix.preRotate(rotationInDegrees);
int bmpWidth = 0;
try {
assert bitmap != null;
bmpWidth = bitmap.getWidth();
} catch (NullPointerException e) {
e.printStackTrace();
}
Bitmap adjustedBitmap = bitmap;
if (bmpWidth > 0)
adjustedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
return adjustedBitmap;
}
/*Then you has the image in Bitmap, you can use the solution below or if Picasso doesn't allows you to put Bitmap you can pass it directly to the ImageView as a Bitmap.*/
ImageView imageView = view.findViewById(R.id.imageViewId);
/*Then use Picasso to draw the image into the ImageView*/
Picasso.with(context).load(url).fit().into(imageView );
This is the dependency for build.gradle, not sure if is the last version but you could try.
implementation 'com.squareup.picasso:picasso:2.5.2'
Kind regards!
Identify the following questions:
Using URL to get bytes to load images
I wrote down what I can with reference to
class DownLoadImageTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
imageView.setImageBitmap(bitmap);
}
#Override
protected Bitmap doInBackground(String... strings) {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(strings[0]).build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
InputStream inputStream = response.body().byteStream();
return BitmapFactory.decodeStream(inputStream);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
This is the URL I use
https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/440px-Image_created_with_a_mobile_phone.png
https://upload.wikimedia.org/wikipedia/commons/3/3a/Cat03.jpg
I can test it. I hope it can help you
Related
First of all I would like to say, that loading big images strategy is described here. I am aware of the obligation to resize the image to omit OutOfMemoryError. I would like to get bytes from the image to be able to send it through Internet.
public byte[] getAttachment(Context context, String fullFilePath) {
byte[] fileBytes = mFileUtil.readFileAsBytes(fullFilePath);
if (fileBytes == null) {
Logger.i("Unable to get bytes, trying through content resolver");
try {
fileBytes = mFileUtil.readFileFromContentResolver(context, fullFilePath);
} catch (OutOfMemoryError e) {
Uri imageUri = Uri.parse(fullFilePath);
if (checkIfFileIsImage(context, imageUri)) {
try {
InputStream stream = context.getContentResolver().openInputStream(imageUri);
if (stream == null) {
return null;
}
BitmapFactory.Options options = getOptions(stream, 2000, 2000);
stream.close();
stream = context.getContentResolver().openInputStream(imageUri);
if (stream == null) {
return null;
}
Bitmap bitmap = BitmapFactory.decodeStream(stream, null, options);
bitmap = rotateBitmap(context, imageUri, bitmap);
stream.close();
fileBytes = convertBitmapToArray(bitmap);
} catch (Exception e1) {
Logger.e("Unable to get bytes using fallback method, attachment " +
"will not be added");
} catch (OutOfMemoryError e2) {
Logger.e("Unable to get bytes using fallback method, because " +
"attachment is too big. Attachment will not be added");
}
}
System.gc();
}
}
return fileBytes;
}
FileUtil.class
public byte[] readFileAsBytes(String fileName) {
File originalFile = new File(fileName);
byte[] bytes = null;
try {
FileInputStream fileInputStreamReader = new FileInputStream(originalFile);
bytes = new byte[(int) originalFile.length()];
fileInputStreamReader.read(bytes);
} catch (IOException e) {
}
return bytes;
}
public byte[] readFileFromContentResolver(Context context, String fileName) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
InputStream is = null;
InputStream inputStream = null;
try {
inputStream = context.getContentResolver().openInputStream(Uri.parse(fileName));
is = new BufferedInputStream(inputStream);
byte[] data = new byte[is.available()];
is.read(data);
bos.write(data);
} catch (Exception e) {
} finally {
try {
if (is != null) {
is.close();
}
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e1) {
}
}
return bos.toByteArray();
}
As you can see the aim of this code is to get byte[] from Bitmap unlike here. It works without problems in almost any case. However it is especially error prone on low-end devices with older Android systems (but also very rarely).
I don't like the idea of setting largeHeap inside AndroidManifest.xml as this is just masking the problem rather than cope with it. I also would not like to send even smaller images.
Could this piece of code be improved in any other way in order to get rid of OutOfMemoryError?
I'm getting a twitter feed in my Android Studio app, using Fabric
for each tweet that has an image attactched, I wish to display the image
how can I extract either a url to the image or a byte[]?
I have found what looks like an array of bytes, but when I attempt to decode it using bitmaps decodeByteArray, it returns null
String mediaString = t.entities.media.toString();
String[] mediaArray = mediaString.split("(?=#)");
byte[] mediaBytes = mediaArray[1].getBytes();
can anybody help me find a way to retrieve the image so I can display it?
Image url
String mediaImageUrl = tweet.entities.media.get(0).url;
Bitmap mediaImage = getBitmapFromURL(mediaImageUrl);
Bitmap mImage = null;
Decode the image
private Bitmap getBitmapFromURL(final String mediaImageUrl) {
try {
Thread t = new Thread() {
public void run() {
try {
URL url = new URL(mediaImageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
mImage = BitmapFactory.decodeStream(input, null, options);
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
} catch (Exception e) {
e.printStackTrace();
}
return mImage;
}
i am getting image only if it is available like:
String mediaImageUrl = null;
if (tweet.entities.media != null) {
String type = tweet.entities.media.get(0).type;
if (type.equals("photo")) {
mediaImageUrl = tweet.entities.media.get(0).mediaUrl;
}
else {
mediaImageUrl = "'";
}
System.out.println("mediaImageUrl" + mediaImageUrl);
}
If u using type attributes u can easily differentiates image/video from userTimeLine
I am using volley library and displaying image successfully. I want to get same downloaded image from cache . This is my code :
private Bitmap getBitmapFromUrl(String url){
String str = "" ;
Bitmap bitmap = null ;
byte[] bytes = null ;
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(url);
try {
str = new String(entry.data, "UTF-8");
bytes = str.getBytes("UTF_8") ;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
bitmap = BitmapFactory.decodeByteArray( bytes, 0,bytes.length,options);
Log.i(PostItemAdapter.class.getSimpleName(), bitmap+"");
return bitmap ;
}
My issue is that the bitmap object is null .
Can any one tell me why ? thanks in advance .
My problem solved using the aid of this great link where I copied the three files in their images package :
DiskLruImageCache
ImageCacheManager
BitmapLruImageCache
Also I copied RequestManager file. Also there was an issue faced me in the DiskLruImageCache when creating the key from the URL, and I solved this by replacing few lines in this file.
The solution
-old code:
First
#Override
public Bitmap getBitmap( String key ) {
Bitmap bitmap = null;
DiskLruCache.Snapshot snapshot = null;
try {
snapshot = mDiskCache.get( key );
....... etc
Second
#Override
public void putBitmap( String key, Bitmap data ) {
DiskLruCache.Editor editor = null;
try {
editor = mDiskCache.edit( key );
......etc
-new code:
First
#Override
public Bitmap getBitmap( String key ) {
Bitmap bitmap = null;
DiskLruCache.Snapshot snapshot = null;
try {
snapshot = mDiskCache.get( ImageCacheManager.getInstance().createKey(key) );
....etc
Second
#Override
public void putBitmap( String key, Bitmap data ) {
DiskLruCache.Editor editor = null;
try {
editor = mDiskCache.edit( ImageCacheManager.getInstance().createKey(key) );
.....etc
Note : All this modification in DiskLruImageCache , Beside the caching you can save images to SD Card by this function :
private void saveImageToSD(Bitmap bmp) {
bytes = new ByteArrayOutputStream();
bmp.compress(mCompressFormat, 90, bytes);
file = new File(Environment.getExternalStorageDirectory()+File.separator+"myImage"+(++i)+".jpg");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
/*--- create a new FileOutputStream and write bytes to file ---*/
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write(bytes.toByteArray());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
And calling to this function be inside the getBitmap(String URL) function witch inside the DiskLruImageCache file .
I previously worked on fetching image from sd card displaying it in a list view, that worked using:
imgView.setImageURI(Uri.parse(ImagePath));
Now, I am trying to display image from URL, with the following lines but the image is not displayed in the list view, the following are the lines used:
imgView.setImageBitmap(getBitmapFromURL(ImagePath));
Where, getBitmapFromURL is:
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
}
catch (IOException e) {
e.printStackTrace();
return null;
}
}
There is no exception displayed, the image just not get displayed.
Need of an urgent solution....
Thanks,
This is a synchronous loading.(Personally I would not use this cause if there are so many Image to be loaded, the apps is a bit laggy)..
URL url = new URL(//your URL);
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bmp);//your imageview
If I were you I would study Async or the lazy adapter..
EDIT
I forgot where I got these code (well thank you for a wonderful code author)
Here it is
public Bitmap getBitmap(String bitmapUrl) {
try {
URL url = new URL(bitmapUrl);
return BitmapFactory.decodeStream(url.openConnection().getInputStream());
}
catch(Exception ex) {return null;}
}
public enum BitmapManager {
INSTANCE;
private final Map<String, SoftReference<Bitmap>> cache;
private final ExecutorService pool;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
private Bitmap placeholder;
BitmapManager() {
cache = new HashMap<String, SoftReference<Bitmap>>();
pool = Executors.newFixedThreadPool(5);
}
public void setPlaceholder(Bitmap bmp) {
placeholder = bmp;
}
public Bitmap getBitmapFromCache(String url) {
if (cache.containsKey(url)) {
return cache.get(url).get();
}
return null;
}
public void queueJob(final String url, final ImageView imageView,
final int width, final int height) {
/* Create handler in UI thread. */
final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
String tag = imageViews.get(imageView);
if (tag != null && tag.equals(url)) {
if (msg.obj != null) {
imageView.setImageBitmap((Bitmap) msg.obj);
} else {
imageView.setImageBitmap(placeholder);
Log.d(null, "fail " + url);
}
}
}
};
pool.submit(new Runnable() {
public void run() {
final Bitmap bmp = downloadBitmap(url, width, height);
Message message = Message.obtain();
message.obj = bmp;
Log.d(null, "Item downloaded: " + url);
handler.sendMessage(message);
}
});
}
public void loadBitmap(final String url, final ImageView imageView,
final int width, final int height) {
imageViews.put(imageView, url);
Bitmap bitmap = getBitmapFromCache(url);
// check in UI thread, so no concurrency issues
if (bitmap != null) {
Log.i("inh","Item loaded from cache: " + url);
imageView.setImageBitmap(bitmap);
} else {
imageView.setImageBitmap(placeholder);
queueJob(url, imageView, width, height);
}
}
private Bitmap downloadBitmap(String url, int width, int height) {
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(
url).getContent());
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
Log.i("nandi2 ako", ""+bitmap);
cache.put(url, new SoftReference<Bitmap>(bitmap));
return bitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Now to call it
String fbAvatarUrl = "//Your URL";
BitmapManager.INSTANCE.loadBitmap(fbAvatarUrl, //Your ImageView, 60,60);
//60 60 is my desired height and width
I encountered this kind problem before, you can refer to this thread, if no luck, try my code,
public static Bitmap loadImageFromUrl(String url) {
URL m;
InputStream i = null;
BufferedInputStream bis = null;
ByteArrayOutputStream out =null;
try {
m = new URL(url);
i = (InputStream) m.getContent();
bis = new BufferedInputStream(i,1024 * 8);
out = new ByteArrayOutputStream();
int len=0;
byte[] buffer = new byte[1024];
while((len = bis.read(buffer)) != -1){
out.write(buffer, 0, len);
}
out.close();
bis.close();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
byte[] data = out.toByteArray();
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
return bitmap;
}
I used the code below to fetch the image from a url but it doesn't working for large images.
Am I missing something when fetching that type of image?
imgView = (ImageView)findViewById(R.id.ImageView01);
imgView.setImageBitmap(loadBitmap("http://www.360technosoft.com/mx4.jpg"));
//imgView.setImageBitmap(loadBitmap("http://sugardaddydiaries.com/wp-content/uploads/2010/12/how_do_i_get_sugar_daddy.jpg"));
//setImageDrawable("http://sugardaddydiaries.com/wp-content/uploads/2010/12/holding-money-copy.jpg");
//Drawable drawable = LoadImageFromWebOperations("http://www.androidpeople.com/wp-content/uploads/2010/03/android.png");
//imgView.setImageDrawable(drawable);
/* try {
ImageView i = (ImageView)findViewById(R.id.ImageView01);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL("http://sugardaddydiaries.com/wp-content/uploads/2010/12/holding-money-copy.jpg").getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
System.out.println("hello");
} catch (IOException e) {
System.out.println("hello");
}*/
}
protected Drawable ImageOperations(Context context, String string,
String string2) {
// TODO Auto-generated method stub
try {
InputStream is = (InputStream) this.fetch(string);
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
You're trying to download the Large Image from within the UI Thread....This will cause an ANR (Application not Responding)
Use AsyncTask to download the images, that way, a seperate thread will be used for the download and your UI Thread wont lock up.
see this good example that loads image from server.
blog.sptechnolab.com/2011/03/04/android/android-load-image-from-url/.
If you want to download the image very quickly then you can use AQuery which is similar to JQuery just download the android-query.0.15.7.jar
Import the jar file and add the following snippet
AQuery aq = new AQuery(this);
aq.id(R.id.image).image("http://4.bp.blogspot.com/_Q95xppgGoeo/TJzGNaeO8zI/AAAAAAAAADE/kez1bBRmQTk/s1600/Sri-Ram.jpg");
// Here R.id.image is id of your ImageView
// This method will not give any exception
// Dont forgot to add Internet Permission
public class MyImageActivity extends Activity
{
private String image_URL= "http://home.austarnet.com.au/~caroline/Slideshows/Butterfly_Bitmap_Download/slbutfly.bmp";
private ProgressDialog pd;
private Bitmap bitmap;
private ImageView bmImage;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bmImage = (ImageView)findViewById(R.id.imageview);
pd = ProgressDialog.show(this, "Please Wait", "Downloading Image");
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { image_URL });
// You can also give more images in string array
}
private class DownloadWebPageTask extends AsyncTask<String, Void, Bitmap>
{
// String --> parameter in execute
// Bitmap --> return type of doInBackground and parameter of onPostExecute
#Override
protected Bitmap doInBackground(String...urls) {
String response = "";
for (String url : urls)
{
InputStream i = null;
BufferedInputStream bis = null;
ByteArrayOutputStream out =null;
// Only for Drawable Image
// try
// {
// URL url = new URL(image_URL);
// InputStream is = url.openStream();
// Drawable d = Drawable.createFromStream(is, "kk.jpg");
// bmImage.setImageDrawable(d);
// }
// catch (Exception e) {
// // TODO: handle exception
// }
// THE ABOVE CODE IN COMMENTS WILL NOT WORK FOR BITMAP IMAGE
try
{
URL m = new URL(image_URL);
i = (InputStream) m.getContent();
bis = new BufferedInputStream(i, 1024*8);
out = new ByteArrayOutputStream();
int len=0;
byte[] buffer = new byte[4096];
while((len = bis.read(buffer)) != -1)
{
out.write(buffer, 0, len);
}
out.close();
bis.close();
byte[] data = out.toByteArray();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
}
catch (Exception e)
{
e.printStackTrace();
}
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result)
{
if(result!=null)
bmImage.setImageBitmap(result);
pd.dismiss();
}
}
}