Saving image from httpResponce - android

I have to download image from httpResponse and save it on internal storage on android device. I have this block of code trying to do that:
HttpResponse httpResponse = httpClient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
Bitmap logo = BitmapFactory.decodeStream(inputStream);
FileOutputStream fos = null;
try {
fos = getApplicationContext().openFileOutput("logo.png",Context.MODE_PRIVATE);
logo.compress(Bitmap.CompressFormat.PNG, 90, fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
fos.close();
}
But I dont get the result I need. Saved image is does not open with image viewvers and its slighly bigger in size too. Image to download is 1.71 KB and the result is 2.01 KB. any ideas?

I don't know what's the real problem in your code but you can try this code if you want,this code ran without any problem for me
To save into internal memory...
File fileWithinMyDir = getApplicationContext().getFilesDir();
try
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
URL url = new URL("http://t2.gstatic.com /images?q=tbn:ANd9GcQjZgUffqqe2mKKb5VOrDNd-ZxD7sJOU7WAHlFAy6PLbtXpyQZYdw");
File file = new File( fileWithinMyDir.getAbsolutePath() + "/" +"sun.jpg");
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1)
{
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
}
catch (IOException e)
{
Log.e("download", e.getMessage());
}
To load image from internal memory..
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
mImgView1 = (ImageView) findViewById(R.id.mImgView1);
Bitmap bitmap = BitmapFactory.decodeFile(fileWithinMyDir.getAbsolutePath() + "/" +"sunn"+".file extension");
mImgView1.setImageBitmap(bitmap);

Related

download and store image from url

I want to download an image from the given url. the downloaded image should save in SD card. I have used the below code.
URL newurl = null;
try {
newurl = new URL(strHitRes);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection connection = (HttpURLConnection) newurl.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
Toast.makeText(getApplicationContext(),"download successful",Toast.LENGTH_LONG).show();
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
But image is not downloading. Even i tested in debug mode, i found that my bitmap is null. How to solve this.
Say thanks to Vineet for his answer
try {
URL url = new URL("url from apk file is to be downloaded");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "filename.ext");
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//To download bitmap from URL
public Bitmap getbmpfromURL(String surl){
try {
URL url = new URL(surl);
HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
urlcon.setDoInput(true);
urlcon.connect();
InputStream in = urlcon.getInputStream();
Bitmap mIcon = BitmapFactory.decodeStream(in);
return mIcon;
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
return null;
}
}
To save bitmap to SD card
private void SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
String fname = "Image.jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
And don't forget to use below permission in your manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />

video download from google+/picasa android

We have a requirement to download video from google+/picasa and store it into sdcard.
Can you please any one help me to solve this issue?
google+/picasa
Converting from URI to byte[], then byte[] is stored to file:
InputStream videoStream = getActivity().getContentResolver().openInputStream(videoUri);
byte bytes[] = ByteStreams.toByteArray(videoStream );
videoFile = new File("abcd.mp4");
FileOutputStream out = new FileOutputStream(videoFile);
out.write(bytes);
out.close();
Can you try that one :
public String DownloadFromUrl(String DownloadUrl, String fileName) {
File SDCardRoot = null;
try {
SDCardRoot = Environment.getExternalStorageDirectory();
File files = new File(SDCardRoot+fileName);
int sizeoffile;
if(!files.exists())
{
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath());
if(dir.exists()==false) {
dir.mkdirs();
}
URL url = new URL(DownloadUrl);
File file = new File(dir, fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
sizeoffile = ucon.getContentLength();
Log.d("SIZEOFFILE: ", sizeoffile+" BYTE");
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
}
}
catch (IOException e) {
e.getMessage();
}
return SDCardRoot+fileName; }
Finally i found the solution.
Uri videoUri = data.getData();
File videoFile = null;
final InputStream imageStream;
try {
imageStream = getActivity().getContentResolver().openInputStream(videoUri);
byte bytes[] = ByteStreams.toByteArray(imageStream);//IStoByteArray(imageStream);
videoFile = new File(Environment.getExternalStorageDirectory()+ "/"+System.currentTimeMillis()+".mp4");
videoFile.createNewFile();
FileOutputStream out = new FileOutputStream(videoFile);
out.write(bytes);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (Exception ee){
ee.printStackTrace();
}
I have recently encountered this.
I first discovered that what I'm receiving is a picture rather than a video.
But I didn't understand why Facebook is successfully playing the online video I shared via (Google+'s) Photo.
I then occasionally discovered that the file they're currently giving is a GIF with the original extension in the MediaStore.Images.Media.DISPLAY_NAME section of the contentUri.
Eeek!

cant load the image from sqlite database in android

I tried to load an image from an database but the image is not loading,the logcat shows null
is it simethinf with the way i programmed..
imgdisplay = (ImageView) findViewById(R.id.imgIcon);
myDB = this.openOrCreateDatabase("hello", MODE_PRIVATE, null);
Cursor c = myDB.rawQuery(
"SELECT image FROM employee_details WHERE name= 'vv'", null);
if (c.getCount() > 0) {
c.moveToFirst();
do {
byte[] blob = c.getBlob(c.getColumnIndex("image"));
ImageView iv = (ImageView) findViewById(R.id.imgIcon);
iv.setImageBitmap(BitmapFactory.decodeByteArray(blob, 0,blob.length));
} while (c.moveToNext());
}
c.close();
myDB.close();
Logcat error is...
08-02 04:51:25.471: D/skia(8433): --- SkImageDecoder::Factory returned null
try below code..
byte[] Image_bytes = cursor.getBlob(cursor.getColumnIndex("image"));
ImageView iv = (ImageView) findViewById(R.id.imgIcon);
iv.setImageBitmap(new ImageConversation().convertArrayToBmp(Image_bytes));
...
public Bitmap convertArrayToBmp(byte[] array) {
Bitmap bitmap = BitmapFactory.decodeByteArray(array, 0, array.length);
return bitmap ;
}
use following loop
c.moveToFirst();
while(!c.isAfterLast()) {
byte[] blob = c.getBlob(c.getColumnIndex("image"));
ImageView iv = (ImageView) findViewById(R.id.imgIcon);
iv.setImageBitmap(BitmapFactory.decodeByteArray(blob, 0,blob.length));
c.moveToNext()
}
Try doing something like this -
If you are storing your image as String in database
if(image.isEmpty())
{
System.out.println("is empty image");
}
else
{
byte[] decodedByte = Base64.decode(image, 0);
Bitmap bm = BitmapFactory.decodeByteArray(decodedByte, 0,
decodedByte.length);
iv.setImageBitmap(bm);
}
I didn't find a method to save the image to the database so I started to save the image directly to the internal memory,this is not the answer for the question but may give some ideas to others who also don't have any idea to do...
To save into internal memory...
File fileWithinMyDir = getApplicationContext().getFilesDir();
try
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
URL url = new URL("http://t2.gstatic.com /images?q=tbn:ANd9GcQjZgUffqqe2mKKb5VOrDNd-ZxD7sJOU7WAHlFAy6PLbtXpyQZYdw");
File file = new File( fileWithinMyDir.getAbsolutePath() + "/" +"sun.jpg");
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1)
{
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
}
catch (IOException e)
{
Log.e("download", e.getMessage());
}
To load image from internal memory..
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
mImgView1 = (ImageView) findViewById(R.id.mImgView1);
Bitmap bitmap = BitmapFactory.decodeFile(fileWithinMyDir.getAbsolutePath() + "/" +"sunn"+".file extension");
mImgView1.setImageBitmap(bitmap);
This is for newer android's that show error due to " android.os.networkonmainthreadexception"
u can also use AsyncTask if u want to solve the problem...

android - storing image in internal storage

I an trying to store images downloaded from web to internal storage. I am refer following solution android - storing image cache in internal memory and reusing it
but still i am getting exception :
07-19 12:05:47.729: E/AndroidRuntime(341): java.lang.IllegalArgumentException: File /data/data/com.yellow.activity/files/-1717792749 contains a path separator
How to load image from filepath :
here is my code . image is an arraylist of URLs.
File fileWithinMyDir = getApplicationContext().getFilesDir();
for(int i=0; i<image.size();i++){
String filename = String.valueOf(image.get(i).hashCode());
String urlString = image.get(i);
String PATH = fileWithinMyDir.getAbsolutePath() + "/" +filename;
infoLog(PATH);
DownloadFromUrl(PATH, urlString);
img_path.add(PATH);
}
private void DownloadFromUrl(String fileName, String urlStr)
{
try
{
URL url = new URL(urlStr);
File file = new File(fileName);
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1)
{
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file,true);
fos.write(baf.toByteArray());
fos.close();
infoLog("going ryt....");
}
catch (IOException e)
{
infoLog("download "+ e.getMessage());
}
}
how to load image to imageView? I tried.
File filePath = getFileStreamPath(img_path.get(i));
imageView.setImageDrawable(Drawable.createFromPath(filePath.toString()));
but it didn't work.
To save into internal memory...
File fileWithinMyDir = getApplicationContext().getFilesDir();
try
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
URL url = new URL("http://t2.gstatic.com /images?q=tbn:ANd9GcQjZgUffqqe2mKKb5VOrDNd-ZxD7sJOU7WAHlFAy6PLbtXpyQZYdw");
File file = new File( fileWithinMyDir.getAbsolutePath() + "/" +"sun.jpg");
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1)
{
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
}
catch (IOException e)
{
Log.e("download", e.getMessage());
}
To load image from internal memory..
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
mImgView1 = (ImageView) findViewById(R.id.mImgView1);
Bitmap bitmap = BitmapFactory.decodeFile(fileWithinMyDir.getAbsolutePath() + "/" +"sunn"+".file extension");
mImgView1.setImageBitmap(bitmap);
This is for newer android's that show error due to " android.os.networkonmainthreadexception"
u can also use AsyncTask if u want to solve the problem...
Try this way
String PATH = fileWithinMyDir.getAbsolutePath() + filename;
I solved it.
Replace following code
File filePath = getFileStreamPath(img_path.get(i));
imageView.setImageDrawable(Drawable.createFromPath(filePath.toString()));
with
imageView.setImageDrawable(Drawable.createFromPath(img_path.get(i)));

Convert a BufferedInputStream to a File

I am loading a image from the web to the local android phone. The code that I have for writing to a file is as follows
BufferedInputStream bisMBImage=null;
InputStream isImage = null;
URL urlImage = null;
URLConnection urlImageCon = null;
try
{
urlImage = new URL(imageURL); //you can write here any link
urlImageCon = urlImage.openConnection();
isImage = urlImageCon.getInputStream();
bisMBImage = new BufferedInputStream(isImage);
int dotPos = imageURL.lastIndexOf(".");
if (dotPos > 0 )
{
imageExt = imageURL.substring(dotPos,imageURL.length());
}
imageFileName = PATH + "t1" + imageExt;
File file = new File(imageFileName);
if (file.exists())
{
file.delete();
Log.d("FD",imageFileName + " deleted");
}
ByteArrayBuffer baf = new ByteArrayBuffer(255);
Log.d("IMAGEWRITE", "Start to write image to Disk");
int current = 0;
try
{
while ((current = bisMBImage.read()) != -1)
{
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
Log.d("IMAGEWRITE", "Image write to Disk done");
}
catch (IOException e)
{
e.printStackTrace();
}
isImage.close();
}
catch (IOException e)
{
Log.d("DownloadImage", "Error: " + e);
}
finally
{
isImage = null;
urlImageCon = null;
urlImage = null;
}
For some reason the whole writing to a file takes 1 minute. Is there a way I can optimize this ?
Your buffer is very small: 255 bytes. You could make it 1024 times bigger (255 kilobytes). This is an acceptable size and this would certainly speed up the thing.
Also, this is very slow as it reads the bytes one by one:
while ((current = bisMBImage.read()) != -1) {
baf.append((byte) current);
}
You should try using the array version of read() instead: read(byte[] buffer, int offset, int byteCount) with an array as large as what I have described above.
You should use the Android HttpClient for file fetching over the java URL Connection. Also your Buffer is very small.
Try this snipped:
FileOutputStream f = new FileOutputStream(new File(root,"yourfile.dat"));
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(urlString);
HttpResponse response = httpClient.execute(request);
InputStream is = response.getEntity().getContent();
byte[] buffer = new byte[1024];
int len1 = 0;
while ( (len1 = is.read(buffer)) > 0 ) {
f.write(buffer,0, len1);
}
f.close();

Categories

Resources