Hey there- I'm attempting to load an image within a Live Wallpaper via a URL... is it possible? If so can you tell my why this code isn't working (Log - "Could not load Bitmap from: " + url)? Thanks!
Engine - Runnable - run():
...
c = holder.lockCanvas();
if (c != null) {
try {
final Bitmap b = BitmapUtils.loadBitmap("http://mw2.google.com/mw-panoramio/photos/medium/17287086.jpg");
c.drawBitmap(b, 0, 0, null);
} catch (Exception e) {
Log.e("Debug", e.toString());
}
}
...
BitmapUtils
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
Yes, it is possible. I do it all the time. :-)
Probably your "issue" is that you have neglected to put
<uses-permission android:name="android.permission.INTERNET" />
in your AndroidManifest.xml
Related
I have been having trouble converting the base64 String Image that is being sent to me by the backend.
So this is how the backend sends the data.
final ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(img, formatName, Base64.getEncoder().wrap(os));
return os.toString(StandardCharsets.ISO_8859_1.name());
} catch (final IOException ioe) {
throw new UncheckedIOException(ioe);
}
And this is how we convert it.
final byte[] data = Base64.decode(base64, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(data, 0, data.length);
The result is always null. Any help is highly appreciated.
EDIT:
These are the back end codes.
#Override
public BufferedImage base64ToImage(String base64Image) throws IOException {
byte[] imageBytes = Base64.getDecoder().decode(base64Image);
BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageBytes));
return img;
}
public static String imgToBase64String(final RenderedImage img, final String formatName) {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(img, formatName, Base64.getEncoder().wrap(os));
return os.toString();
} catch (final IOException ioe) {
throw new UncheckedIOException(ioe);
}
}
And this is our converting tool before sending the Base64 Image String to the back end.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
return Base64.encodeToString(baos.toByteArray(), Base64.NO_WRAP);
Check that ur base64 encoded string does not start with data:image/jpg;base64,. If it does then remove it. The Base64.decode won't be able to decode it in this case. u can remove it by using encodedString.substring(encodedString.indexOf(",") + 1);. Let me know if this solves ur problem.
Try this,
ImageView driverImage = (ImageView) driverReportView.findViewById(R.id.imgViewDriverImage);
try {
byte [] encodeByte = Base64.decode(driverImageString.replace("\'/", "/"), Base64.DEFAULT);
Bitmap bitmap= BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
if (bitmap != null)
driverImage.setImageBitmap(bitmap);
}catch (Exception ex){
Log.e(TAG,"Error to display driver info "+ex.toString());
}
Where
driverImageString is your image string
I am doing an android app which involves a concept where I have to extract numbers from the captured image. Can you please help me or guide me a link where I could find the appropriate tutorials?
You have a good tutorial here where is explains method to create, to reading and writting files, in your case needs to read.
When you read this tutorial try my code that return a string of bytes:
public String formatPhoto_JPEGtoByteArray (String uri){
// Read bitmap from file
Bitmap bitmap = null;
InputStream stream = null;
ByteArrayOutputStream byteStream = null;
try {
stream = new BufferedInputStream(new FileInputStream(new File(uri)));
bitmap = BitmapFactory.decodeStream(stream);
byteStream = new ByteArrayOutputStream();
Matrix matrix = new Matrix();
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteStream);
// Convert ByteArrayOutputStream to byte array. Close stream.
byte[] byteArray = byteStream.toByteArray();
Log.e("-- FilesAndFolders.formatPhoto_JPEGtoByteArray --", "Last file of size: " + byteArray.length);
String imageEncoded = Base64.encodeToString(byteArray, Base64.NO_WRAP);
byteStream.close();
byteStream = null;
return imageEncoded;
}
catch (IOException ex) {
Log.e("-- FilesAndFolders.formatPhoto --", "Exception with " + uri,ex);
return null;
}
catch (Exception ex){
Log.e("-- FilesAndFolders.formatPhoto --", "Exception with " + uri,ex);
return null;
}
finally {
try {
if (stream != null) stream.close();
if (byteStream != null) byteStream.close();
} catch (Exception e) {}
}
}
Tell me if I helped you and good programming!
I was wondering how i set a buttons background image from a URL on android.
The buttons id is blue if you need to know that.
I tried this but it didn't work.
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
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(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
I used the next code for obtain the bitmap, one important thing is sometimes you can't obtain the InputStream, and that is null, I make 3 attemps if that happens.
public Bitmap generateBitmap(String url){
bitmap_picture = null;
int intentos = 0;
boolean exception = true;
while((exception) && (intentos < 3)){
try {
URL imageURL = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageURL.openConnection();
conn.connect();
InputStream bitIs = conn.getInputStream();
if(bitIs != null){
bitmap_picture = BitmapFactory.decodeStream(bitIs);
exception = false;
}else{
Log.e("InputStream", "Viene null");
}
} catch (MalformedURLException e) {
e.printStackTrace();
exception = true;
} catch (IOException e) {
e.printStackTrace();
exception = true;
}
intentos++;
}
return bitmap_picture;
}
Don't load the image directly in the UI (main) thread, for it will make the UI freeze while the image is being loaded. Do it in a separate thread instead, for example using an AsyncTask. The AsyncTask will let the image load in its doInBackground() method and then it can be set as the button background image in the onPostExecute() method. See this answer: https://stackoverflow.com/a/10868126/2241463
Try this code:
Bitmap bmpbtn = loadBitmap(yoururl);
button1.setImageBitmap(bmpbtn);
I thought this wouldn't be too hard but have been banging my head against a desk for the last few hours and would really appreciate some help. Essentially, I want to get an image from a url, save it to internal memory (not sd card) and be able to retrieve that image and show it using an ImageView at a later time.
This is how I get the pictures from a url and write them to memory(urls are stored in "pics"):
String urlstring = pics[l][w];
if (urlstring != null){
try {
URL url = new URL(urlstring);
InputStream input = url.openStream();
FileOutputStream output = openFileOutput(("specimage"+l) + ("" +w+".jpg"), MODE_PRIVATE);
byte[] buffer = new byte[input.available()];
int n = input.read(buffer, 0, buffer.length);
while (n >= 0) {
output.write(buffer, 0, buffer.length);
n = input.read(buffer, 0, buffer.length);
}
output.close();
input.close();
} catch (Exception e) {
GlobalState.popupMessage(homePage, "Error", "Files could not be stored on disk");
}
}
This is how I attempt to retrieve them (path is the filename):
private Bitmap getPic(String path){
FileInputStream in;
Bitmap bMap = null;
BufferedInputStream buf;
try {
in = openFileInput(path);
buf = new BufferedInputStream(in);
byte[] bMapArray= new byte[buf.available()];
buf.read(bMapArray);
bMap = BitmapFactory.decodeStream(buf);
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (Exception e) {
System.out.println("excep.");
}
if (bMap == null) System.out.println("null");
return bMap;
}
If I do this the picture does not show up, but the program does not crash. An exception is not triggered. However, the value of bMap is given as null. I also get this strange message in the log:
DEBUG/skia(19358): --- SkImageDecoder::Factory returned null
Please let me know what I'm doing wrong. I have been ransacking my brain to no avail.
I should mention I do setImageBitmap in the ui thread.
Just try this, (Replace with your) and let me know what happen,
ImageView img = (ImageView)findViewById(R.id.imgView1);
FileInputStream in;
Bitmap bMap = null;
BufferedInputStream buf;
try {
in = openFileInput("icon.png");
buf = new BufferedInputStream(in);
byte[] bMapArray= new byte[buf.available()];
buf.read(bMapArray);
bMap = BitmapFactory.decodeByteArray(bMapArray,0,bMapArray.length);
img.setImageBitmap(bMap);
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (Exception e) {
System.out.println("excep.");
}
I use such code for downloading image from URL:
public static Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
When I send URL "http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png" it works fine, but when I use "http://www.hospimedica.com/images/stories/articles/article_images/_CC/20110328%20-%20DJB146.gif" it returns me null.
What's wrong with this URL?
Why are you writing your own method to downlaod an image ? Android has inbuilt method to achieve this.. Just use
URL url = new URL("Your url");
Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());