I need to get image from the web and store it in the phone for later use.
I tryed this:
public Drawable grabImageFromUrl(String url) throws Exception
{
return Drawable.createFromStream((InputStream)new URL(url).getContent(), "src");
}
So this my function to grab image from Url, i just need a proccess to get the returned drawable and save.
How can i do that ?
see this complete example give here
http://android-example-code.blogspot.in/p/download-store-and-read-images-from.html
Based off here, you can actually download the image using a different method. Is it absolutely necessary that you store it as a drawable before saving it? Because I think you could save it first, and THEN open it, if need be.
URL url = new URL ("file://some/path/anImage.png");
InputStream input = url.openStream();
try {
//The sdcard directory e.g. '/sdcard' can be used directly, or
//more safely abstracted with getExternalStorageDirectory()
String storagePath = Environment.getExternalStorageDirectory();
OutputStream output = new FileOutputStream (storagePath + "/myImage.png");
try {
byte[] buffer = new byte[aReasonableSize];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}
Related
From the two lines below, in which line the actual download happens ?. and if possible please explain
InputStream input = new java.net.URL(imageURL).openStream();
bitmap = BitmapFactory.decodeStream(input);
This:
InputStream input = new java.net.URL(imageURL).openStream();
Creates a connection to the URL. The result is a stream, that can be used to get the content of the URL.
This:
bitmap = BitmapFactory.decodeStream(input);
Uses the above mentioned stream to read the URL's content and use it to create the bitmap, so this is where the "download" happens. Bear in mind, that this doesn't mean the image is actually saved on the internal memory or SD card. It's just there in memory.
Try this for getting and saving .
Also you can easly work with Universal Image lOader library or picasso
https://github.com/nostra13/Android-Universal-Image-Loader
http://square.github.io/picasso/
URL url = new URL("....your site .....");
InputStream input = null;
FileOutputStream output = null;
try {
String outputName = "thumbnail.jpg";
input = url.openConnection().getInputStream();
output = c.openFileOutput(outputName, Context.MODE_PRIVATE);
int read;
byte[] data = new byte[1024];
while ((read = input.read(data)) != -1)
output.write(data, 0, read);
return outputName;
} finally {
if (output != null)
output.close();
if (input != null)
input.close();
}
first, sorry for my bad english and second, I have a "little" problem.
I tested a lot of codes from StackOverFlow but i continue with the same problem.
I'm trying to download some images from URL. I have an ExpandableListView and I use a class named Downloadusers to download all information about users.
In this class I get the user's photo URL and I download the images with the following code:
private void downloadFile(String url) {
String filepath = null;
try
{
URL nurl = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) nurl.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File SDCardRoot = getExternalFilesDir(null);
String filename = url.substring(url.lastIndexOf('/') + 1);
Log.i("Local filename:",""+filename+" SDCardRoot: "+SDCardRoot.toString());
File file = new File(SDCardRoot,filename);
if(file.createNewFile())
{
file.createNewFile();
}
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[PHOTO_FILE_MAX_SIZE];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 )
{
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
}
fileOutput.close();
if(downloadedSize==totalSize) filepath=file.getPath();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
filepath=null;
e.printStackTrace();
}
Log.i("filepath:"," "+filepath);
}
I have also verified that the URLs are correct and I have loaded in the browser.
With Log.i("filepath:"," "+filepath); I can see that filepath is correct, so I think that images are downloaded correctly but no, image files are corrupt files, so when I go to load the images into my ImageView I have a NullPointException because bMap readed is null due to corrupt images.
I have all permissions: Internet, Write and read external storage and phone state.
I tried too download images with AsyncTask, but I have the same problem.
Someone know what can be my problem?
Thanks.
Here it is my download method. You will download image into SDCARD. You can check whether image is downloaded or not by going DDMS Perspective.
public void download(String Url) throws IOException {
URL url = new URL (Url);
InputStream input = url.openStream();
try {
File storagePath = new File(Environment.getExternalStorageDirectory());
OutputStream output = new FileOutputStream (new File(storagePath, 'myImage.jpg'));
try {
byte[] buffer = new byte[2048];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}
}
This snippet is for showing downloaded image in ImageView.
ImageView image = (ImageView) findViewById(R.id.image);
Bitmap bitmap = BitmapFactory.decodeFile(Environment
.getExternalStorageDirectory() + "myImage.jpg");
image.setImageBitmap(bitmap);
I solved my problem using library nostra13 "universal-image-loader-1.9.2.jar". My code is now:
// If the user photo exists and is public, download and show it.
if (Utils.connectionAvailable(activity)
&& (photoFileName != null) && !photoFileName.equals("")
&& !photoFileName.equals(Constants.NULL_VALUE)) {
// Create options. Setting caché = true (default = false)
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.build();
// Create global configuration and initialize ImageLoader
// with this configuration
ImageLoaderConfiguration config = new ImageLoaderConfiguration
.Builder(activity.getApplicationContext())
.defaultDisplayImageOptions(options)
.build();
ImageLoader.getInstance().init(config);
// Load image, decode it to Bitmap and display Bitmap in ImageView
// (or any other view
// which implements ImageAware interface)
ImageLoader.getInstance().displayImage(photoFileName, image);
}
With that code I can load the image on caché and show in my imageview without problems.
Thanks to all.
I had the same problem, but I was able to solve it by setting
urlConnection.setDoOutput(false);
and it worked, but I don't know why.
I'm quite new to android programming and I have the following problem.
I want to be able to put an image om my server and then if I use my app it should use that image as a background.
From previous research I understand I cant save any files to the drawable file?
So is this even possible?
I am now this far:
URL url = new URL ("http://oranjelan.nl/oranjelan-bg.png");
InputStream input = url.openStream();
try {
String storagePath = Environment.getExternalStorageDirectory();
OutputStream output = new FileOutputStream (storagePath + "/oranjelangb.png");
try {
byte[] buffer = new byte[1000000];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}
But I get the following error
# String storagePath = Environment.getExternalStorageDirectory();
The compiller says cannot convert file to string.
It should be possible. Simple steps may include :-
1) Download image file from server, Store it to SDcard or assets folder.
links for step 1 >> link1 link2
2) Create a Bitmap from the file you downloaded.
3) Set that bitmap as a Background image.
You can pick steps and search on SO there should be lots of answers available.
In my android application, I need to upload a image in my Assets/Drawable/raw folder to the server.
I tried the following:
InputStream fileInputStream;
if(imageChanged) {
File file = New File("filename");
fileInputStream = new FileInputStream(file);
}else {
fileInputStream = ctx.getAssets().open("default.png");
}
int bytesAvailable;
byte[] buffer = new byte[102400];
while((bytesAvailable = fileInputStream.available()) > 0) {
int bufferSize = Math.min(bytesAvailable, 102400);
if(bufferSize<102400){
buffer = new byte[bufferSize];
}
int bytesRead = fileInputStream.read(buffer, 0,bufferSize);
dos.write(buffer, 0, bytesRead);
}
This executes fine. I am able to read the inputstream and write bytes to the DataOutputStream, the image is uploaded to the server.
Anyhow, the image at the server appears to be corrupted - only for the default image (uploaded in the 'else' block. The 'if' block image is not getting corrupted)
I also tried placing default.png in the 'raw' folder and tried the below
fileInputStream = ctx.getResources().openRawResource(R.drawable.default);
Same result here - the image at the server is corrupted.
I am starting to doubt if this is because the default.png is in the application space.
Can I get some help towards the proper way to upload an image in the application space (drawable/asset/raw)?
thanks!
nimi
It might have to do with the buffer size? I tried two different methods to read/write a png from the assets folder and both produced a working image. I used FileOutputStream to write to the sdcard but that should not be an issue.
InputStream is, is2;
FileOutputStream out = null, out2 = null;
try {
//method 1: compressing a Bitmap
is = v.getContext().getAssets().open("yes.png");
Bitmap bmp = BitmapFactory.decodeStream(is);
String filename = Environment.getExternalStorageDirectory().toString()+File.separator+"yes.png";
Log.d("BITMAP", filename);
out = new FileOutputStream(filename);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
//method 2: Plain stream IO
String filename2 = Environment.getExternalStorageDirectory().toString()+File.separator+"yes2.png";
out2 = new FileOutputStream(filename2);
Log.d("BITMAP", filename2);
int r, i=0;
is2 = v.getContext().getAssets().open("yes.png");
while ((r = is2.read()) != -1) {
Log.d ("OUT - byte " + i, "Value: " + r);
out2.write(r);
i++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null)
out.close();
if (out2 != null)
out2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I've got the URL of a .png image, that needs to be downloaded and set as a source of an ImageView. I'm a beginner so far, so there are a few things I don't understand:
1) Where do I store the file?
2) How do I set it to the ImageView in java code?
3) How to correctly override the AsyncTask methods?
Thanks in advance, will highly appreciate any kind of help.
I'm not sure you can explicity build a png from a download. However, here is what I use to download images and display them into Imageviews :
First, you download the image :
protected static byte[] imageByter(Context ctx, String strurl) {
try {
URL url = new URL(urlContactIcon + strurl);
InputStream is = (InputStream) url.getContent();
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = is.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
return output.toByteArray();
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
And then, create a BitMap and associate it to the Imageview :
bytes = imagebyter(this, mUrl);
bm = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
yourImageview.setImageBitmap(bm);
And that's it.
EDIT
Actually, you can save the file by doing this :
File file = new File(fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(imagebyter(this, mUrl));
fos.close();
You can explicity build a png from a download.
bm.compress(Bitmap.CompressFormat.PNG, 100, out);
100 is your compression (PNG's are generally lossless so 100%)
out is your FileOutputStream to the file you want to save the png to.