save image in android - android

This is a code for saving images in SD card if and if not exist.
but i don't know how to read it.
Can anybody help me please.
This is the download file method:
public static String DownLoadFile(String netUrl, String name ) {
try {
//need uses permission WRITE_EXTERNAL_STORAGE
ByteArrayBuffer baf = null;
long startTime = 0;
//get to directory (a File object) from SD Card
File savePath=new File(Environment.getExternalStorageDirectory().getPath()+"/postImages/");
String ext="jpg";
URL url = new URL(netUrl);
//create your specific file for image storage:
File file = new File(savePath, name + "." + ext);
boolean success = true;
if (!savePath.exists()) {
success = savePath.mkdir();
}
if (success) {
if(file.createNewFile())
{
file.createNewFile();
//write the Bitmap
Log.i("file existence", "file does not exist!!!!!!!!!!!");
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
startTime = System.currentTimeMillis();
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();
Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
return file.getAbsolutePath();
}//end of create file if not exists
}//end of if success
} catch (Exception exx) {
if (exx.getMessage() != null) {
} else {
}
}
return null;
}

Try this,
Uri uri = Uri.parse("file:///sdcard/temporary_file.jpg");
img.setImageURI(uri);

if u have image uri so get path from uri like
String Path = fileUri.getPath();
// read file from sdcard
public static byte[] readFromStream(String path) throws Exception { File
file = new File(path); InputStream inputStream = new
FileInputStream(file); ByteArrayOutputStream baos = new
ByteArrayOutputStream(); DataOutputStream dos = new
DataOutputStream(baos); byte[] data = new byte[(int) file.length()]; int
count = inputStream.read(data); while (count != -1) { dos.write(data, 0,
count); count = inputStream.read(data); } return baos.toByteArray(); }

Related

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!

Android download even if does not exist

try {
URL url = new URL("http://URL/Dragonfly.db");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String[] path = url.getPath().split("/");
String _file = path[path.length - 1];
int lengthOfFile = c.getContentLength();
if(lengthOfFile > 0){ // Copy file if Length > 0
String PATH = db.DB_PATH; ;//Environment.getExternalStorageDirectory()+
Log.v("", "PATH: " + PATH);
File file = new File(PATH);
file.mkdirs();
String fileName = "Dragonfly.db";
File outputFile = new File(file , fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
}else{
TestAdapter mDbHelper = new TestAdapter(getBaseContext());
mDbHelper.createDatabase();
}
} catch (IOException e) {
e.printStackTrace();
}
I use this code to update database, downloading a new one. but if i dont have a file on server, it replace the database i have for a new empty one (0bytes).
How can i download the file just if it exist on server?
Try to do a status response check:
int responseCode = c.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
{
// update database replacing the old one with the new one
} else {
// continue to use old database
}

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();

Download image(SSL) and store it on SDcard in Android?

I need to download a single image at time from the Internet and then save it on the SD card. How do I do it? I have made an attempt, but when I try to view that downloaded image, it shows the message, "No Preview Available". Please see my code below:
public class ImgDownloader {
private static final int IO_BUFFER_SIZE = 4 * 1024;
public static final byte[] downloadImage(String imgURL) {
byte[] data = null;
try {
Log.v("Down", "1");
InputStream in = null;
BufferedOutputStream out = null;
in = new BufferedInputStream(new URL(imgURL).openStream(), 8 * 1024);
Log.v("Down", "2");
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
Log.v("Down", "3");
data = dataStream.toByteArray();
// bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
Log.v("Down", "4");
} catch (Exception ex) {
ex.printStackTrace();
// System.out.println("Exception in Image Downloader .."
// +ex.getMessage());
}
return data;
}
private static void copy(InputStream in, OutputStream out)
throws IOException {
byte[] b = new byte[IO_BUFFER_SIZE];
int read;
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
}
}
}
Note:
i have download the image from the SSL connection.
Any ideas? Thanks in advance.
You can try something like
try{
URL url = new URL(downloadUrl); //you can write here any link
File file = new File(absolutePath); //Something like ("/sdcard/file.mp3")
//Create parent directory if it doesn't exists
if(!new File(file.getParent()).exists())
{
System.out.println("Path is created " + new File(file.getParent()).mkdirs());
}
file = new File(absolutePath); //Something like ("/sdcard/file.mp3")
file.createNewFile();
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
FileOutputStream fos = new FileOutputStream(file);
int size = 1024*1024;
byte[] buf = new byte[size];
int byteRead;
while (((byteRead = is.read(buf)) != -1)) {
fos.write(buf, 0, byteRead);
bytesDownloaded += byteRead;
}
/* Convert the Bytes read to a String. */
fos.close();
}catch(IOException io)
{
networkException = true;
continueRestore = false;
}
catch(Exception e)
{
continueRestore = false;
e.printStackTrace();
}
Make the appropriate changes according to your requirement. I use the same code for downloading files from internet and saving it to SDCard.
Hope it helps !!

Categories

Resources