I return a Bitmap object according to a url, and the code for download picture:
URL url = new URL(imageUrlStr);
URLConnection conn = url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream in = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(in);
in.close
Then I save it to sdcard. It is ok to save picture.
Now the problem is it download the picture A when use this url to access. But it now shows another B picture in SDCARD. How to solve this problem?
You can identify images by hash-code. Not a perfect solution, good for the demo
private Bitmap getBitmap(String url) {
String filename = String.valueOf(url.hashCode());
File f = new File(cacheDir, filename);
// from SD cache
Bitmap b = decodeFile(f);
if (b != null)
return b;
// from web
try {
Bitmap bitmap = null;
InputStream is = new URL(url).openStream();
OutputStream os = new FileOutputStream(f);
CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
private void CopyStream(InputStream is, OutputStream os) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
}
}
/** decodes image and scales it to reduce memory consumption*/
private Bitmap decodeFile(File f) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPurgeable = true;
return BitmapFactory.decodeStream(new FileInputStream(f));
} catch (FileNotFoundException e) {
}
return null;
}
Use you just need to use method "getBitmap(String)" with your desired url as String
Related
I have the code for downloading image from URL to SDCard, but my device can set up the image ONLY from bitmap.
The question is how I can consume image from URL directly into SQLite Database and then retreive it as the bitmap?
Thanks for any help
public void getNewLogoFromURL(String logo) throws IOException {
new GetLogo().execute(logo);
}
class GetLogoForReceipt extends AsyncTask <String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
try {
downloadFile(params[0]);
} catch ( IOException e ) {
}
return null;
}
}
public void downloadFile(String url) throws IOException {
DataOutputStream fos = null;
try {
File dest_file = new File("/sdcard/Pictures/applicationLogo.png");
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
fos = new DataOutputStream(new FileOutputStream(dest_file));
fos.write(buffer);
fos.flush();
} finally {
fos.close();
}
}
//Device image settingUp code
String[] fileList = { "applicationLogo.png" };
Bitmap[] bitmap = new Bitmap[fileList.length];
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap2 = BitmapFactory.decodeFile("/sdcard/Pictures/applicationLogo.png", options);
for ( int i = 0; i < fileList.length; i++ ) {
bitmap[i] = bitmap2;
}
int ret;
printer = new LinePrinter();
ret = printer.open(device);
ret = printer.setBitmap(bitmap);
Storing bitmaps/images in sqlite database is a bad idea. Download the image to the sd card and save the location in the data base and retrieve the image from sd card when you required.
The below code shows getting bitmap from sdcard.
public Bitmap createBitMap(String path){
File file = new File(path);
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
return bitmap;
}
url="http://www.nasa.gov/sites/default/files/styles/946xvariable_height/public/ladee_spin_2_in_motion_0_0.jpg?itok=yNhf69rE";
try {
HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
input.close();
return bitmap;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
I was tryning to retreive image from the url but no matter what it always returns null. In debugging mode I have observed that it happens when it tries input.close(); .
How can I possibly get the Image.
This is a proper way to load Bitmap:
InputStream is;
Bitmap bitmap;
is = context.getResources().openRawResource(DRAW_SOURCE);
bitmap = BitmapFactory.decodeStream(is);
try {
is.close();
is = null;
} catch (IOException e) {
}
However, as I see you close stream before finish to decoding it.
If so, use other way:
Bitmap bitmap;
InputStream input = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(input, 8192);
ByteArrayBuffer buff = new ByteArrayBuffer(64);
int current = 0;
while ((current = bis.read()) != -1) {
buff.append((byte)current);
}
byte[] imageData = buff.toByteArray();
bitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
try {
is.close();
is = null;
} catch (IOException e) {
}
BTW, see this post, it should work also
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 want to download image from url and store in sdcard's folder.If folder is not exist make folder and save it.But its giving following exception:
java.io.FileNotFoundException: /mnt/sdcard (Is a directory)
The message is clear. /mnt/sdcard is a directory not a file. You need to create FileOutputStream that writes to a non-directory path.
For example:
//Setting up cache directory to store the image
File cacheDir=new File(context.getCacheDir(),"cache_folder");
// Check if cache folder exists, otherwise create folder.
if(!cacheDir.exists())cacheDir.mkdirs();
// Setting up file to write the image to.
File f=new File(cacheDir, "img.png");
// Open InputStream to download the image.
InputStream is=new URL(url).openStream();
// Set up OutputStream to write data into image file.
OutputStream os = new FileOutputStream(f);
HelperUtil.CopyStream(is, os);
...
/**
* Copy all data from InputStream and write using OutputStream
* #param is InputStream
* #param os OutputStream
*/
public static void CopyStream(InputStream is, OutputStream os)
{
final int buffer_size=1024;
try
{
byte[] bytes=new byte[buffer_size];
for(;;)
{
int count=is.read(bytes, 0, buffer_size);
if(count==-1)
break;
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
}
try something like this
String image_URL="http://chart.apis.google.com/chart?chs=200x200&cht=qr&chl=http%3A%2F%2Fandroid-er.blogspot.com%2F";
String extStorageDirectory;
File file;
Bitmap bm;
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
file=new File(android.os.Environment.getExternalStorageDirectory(),"Your FolderName");
extStorageDirectory = Environment.getExternalStorageDirectory().toString();
}else{
file=YourActivity.this.getCacheDir();
}
if(!file.exists())
file.mkdirs();
extStorageDirectory+="Your FolderName/yourimagename.PNG";
File imageFile = new File(extStorageDirectory);
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
if(bitmap!=null){
imageview.setImageBitmap(bitmap);
}else{
extStorageDirectory = Environment.getExternalStorageDirectory().toString();
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
bm = LoadImage(image_URL, bmOptions);
imageview.setImageBitmap(bm);
OutputStream outStream = null;
file=new File(android.os.Environment.getExternalStorageDirectory(),"Your FolderName");
file=new File(extStorageDirectory, "Your FolderName/yourimagename.PNG");
try {
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
where method are as
private Bitmap LoadImage(String URL, BitmapFactory.Options options)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bitmap;
}
private InputStream OpenHttpConnection(String strURL) throws IOException{
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try{
HttpURLConnection httpConn = (HttpURLConnection)conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
}catch (Exception ex){
Log.e("error",ex.toString());
}
return inputStream;
}
You are giving wrong path when triying to save the picture. IT seems that you use "/mnt/sdcard" whereas it should be something like "/mnt/sdcard/image.jpg"
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
bm = LoadImage(image_url, bmOptions);
extStorageDirectory = Environment.getExternalStorageDirectory()
.toString() + "/image_folder";
OutputStream outStream = null;
File wallpaperDirectory = new File(extStorageDirectory);
wallpaperDirectory.mkdirs();
File outputFile = new File(wallpaperDirectory, "image.PNG");
try {
outStream = new FileOutputStream(outputFile);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
private Bitmap LoadImage(String URL, BitmapFactory.Options options) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bitmap;
}
private InputStream OpenHttpConnection(String strURL) throws IOException {
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
} catch (Exception ex) {
}
return inputStream;
}
Try this one, that will return the External memory if it is exist, otherwise it will return the phone memory directory. The constructor takes Context and the name of the folder that you want to create as parameters. And also try this link, its quite nice stuff about what you need. Image Loader
public class FileCache {
private File cacheDir;
private String applicationDirectory = Config.applicationMainFolder;
public FileCache(Context context, String folderName){
//Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(context.getExternalFilesDir(null), applicationDirectory + folderName);
else
cacheDir = new File(context.getCacheDir(), applicationDirectory + folderName);
if(!cacheDir.exists())
cacheDir.mkdirs();
}
public File getFile(String url){
String filename=String.valueOf(url.hashCode());
File f = new File(cacheDir, filename);
return f;
}
public void clear(){
File[] files=cacheDir.listFiles();
if(files==null)
return;
for(File f:files)
f.delete();
}
}
use this
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
File file=new File(Environment.getExternalStorageDirectory()+path);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100, bytes);
byte b[] = bytes.toByteArray();
try
{
FileOutputStream fos = new FileOutputStream(file);
fos.write(b);
fos.flush();
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
path will be your folder in sdcard and bitamp is object of image
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());