I've searched and tried everything I found about this topic on Google and StackOverflow but I didn't find anyway to make it work.
I have this code but it throws me a FATAL EXCEPTION.
I think that, as I am an Android Rookie there's something I do wrong. Help me please ^^
public void svgPhoto() throws IOException {
String dir = Environment.getExternalStorageDirectory().toString();
OutputStream fos = null;
File file = new File(dir,"downloadImage.JPEG");
Bitmap bm =BitmapFactory.decodeFile("http://perlbal.hi-pi.com/blog-images/3278/gd/1242316719/Chat-chat.jpg");
fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bm.compress(Bitmap.CompressFormat.JPEG, 50, bos);
bos.flush();
bos.close();
public class Download extends AsyncTask
{
#Override
protected Void doInBackground(Void... params)
{
try {
URL url = new URL(imageURL);
file2 = new File(fileName);
long startTime = System.currentTimeMillis();
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* 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(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file2);
fos.write(baf.toByteArray());
fos.close();
Log.d("ImageManager",
"download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
} catch (IOException e) {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
try {
try {
File fileWithinMyDir = getApplicationContext().getFilesDir();
String PATH = fileWithinMyDir.getAbsolutePath();
Drawable d = Drawable.createFromPath(PATH.toString());
Bitmap bmp = ((BitmapDrawable) d).getBitmap();
} catch (Exception e) {
e.printStackTrace();
}
if (dialog != null) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Try next code:
String dir = Environment.getExternalStorageDirectory().toString();
File outputfile = new File(dir+"/downloadImage.JPEG");
OutputStream fOut = null;
try {
fOut = new FileOutputStream(outputfile);
Bitmap bm =BitmapFactory.decodeFile("http://perlbal.hi-pi.com/blog-images/3278/gd/1242316719/Chat-chat.jpg");
bm.compress(CompressFormat.JPEG, 50, fOut);
} catch (IOException e) {
Logger.error(e.getMessage(), e);
}finally{
try {
if(fOut != null){
fOut.flush();
fOut.close();
}
} catch (IOException e) {
Logger.error(e.getMessage(), e);
}
}
Related
At start up of my app I want to extract my images (if they does not exists) from drawable folder to internal app folder to use later with FileProvider. Images have dimensions 2000*2000 and average size 380kb, format png.
Those images are not to be displayed (smaller ones are used to display). They are only for file sharing and I have to keep their original size.
I get out of memory at calling
Bitmap bm = BitmapFactory.decodeResource(getResources(), imageResID);
Code
private void extractImages() {
TypedArray imgs = getResources().obtainTypedArray(R.array.smile_list_share);
File imagePath = new File(getFilesDir(), "images");
File checkImage;
for (int i = 0; i < imgs.length(); i++) {
int imageResID = imgs.getResourceId(i, 0);
if (imageResID > 0) {
String name = getResources().getResourceEntryName(imageResID);
checkImage = new File(imagePath, name + ".png");
if (!checkImage.exists()) {
Bitmap bm = BitmapFactory.decodeResource(getResources(), imageResID);
boolean b = saveBitmapToFile(imagePath, name + ".png", bm, Bitmap.CompressFormat.PNG, 100);
Log.e("mcheck","saved "+b+", file "+name);
Log.e("mcheck", "file does not exists " + name);
} else {
Log.e("mcheck", "file exists " + name);
}
} else {
Log.e("mcheck", "ERROR " + i);
}
}
imgs.recycle();
}
public boolean saveBitmapToFile(File dir, String fileName, Bitmap bm,
Bitmap.CompressFormat format, int quality) {
File imageFile = new File(dir, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(imageFile);
bm.compress(format, quality, fos);
bm.recycle();
fos.close();
return true;
} catch (IOException e) {
Log.e("app", e.getMessage());
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return false;
}
You have to call recycle on your bitmap object everytime you are done with it.
Here is a good guide on how to manipulate bitmaps efficiently
https://developer.android.com/training/displaying-bitmaps/load-bitmap.html
I found that I dont need to create bitmap object at all. It is possible to obtaine intput stream from getResourses directly.
public boolean saveBitmapToFile(File dir, String fileName, int imageResourse) {
File imageFile = new File(dir, fileName);
FileOutputStream fos = null;
InputStream inputStream = null;
try {
fos = new FileOutputStream(imageFile);
inputStream = getResources().openRawResource(imageResourse);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
inputStream.close();
fos.close();
return true;
} catch (IOException e) {
Log.e("app", e.getMessage());
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return false;
}
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(); }
Here's the code to download a 3pg video file. Maybe one can give me an idea about what's wrong with it. I really need help. Can't get it to download the file:
Blockquote
protected String doInBackground(String... sUrl) {
byte[] data = new byte[1024];
int count = 0;
FileOutputStream fos = null;
BufferedOutputStream output = null;
try {
URL url= new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
Log.v("URL"," " + connection.getURL());
Log.v("File ", "length = " + connection.getContentLength());
// download the file
BufferedInputStream input = new BufferedInputStream(connection.getInputStream());
File f = new File(Environment.getExternalStorageDirectory().getPath() + "/twokids.3gp");
f.setWritable(true,true);
try {
fos = new FileOutputStream(f);
} catch (FileNotFoundException fnfe) {
fnfe.getStackTrace();
} catch (SecurityException se) {
se.getStackTrace();
}
output = new BufferedOutputStream(fos);
while ((count = input.read(data)) != -1) {
Log.v("Count="," " + count);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
Log.v("Download","Finished");
} catch (IndexOutOfBoundsException iobe) {
iobe.getStackTrace();
} catch (IOException ioe) {
ioe.getStackTrace();
} catch (NullPointerException npe) {
npe.getStackTrace();
}
catch (Exception e) {
e.getStackTrace();
}
return null;
}
And strangely enough, sometimes the method connection.getContentLength() returns -1 instead of the file length.
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 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 !!