I would like to know what is best way to store images from internet in folder and read from folder because later on I will need to show them in gallery. Should I store them to external or internal storage, should I give user option to choose storage if his memory is low or? Also how should I optimize it so it doesn't take too much space. Generally I need some idea how to make it fast, stable and optimized for devices with no memory card.
in your Oncreate() method
getBitmapFromURL(data);
where data is the image url.
then
public Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
URLConnection connection = (URLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(input);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
String filename;
Date date = new Date(0);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
filename = sdf.format(n);
File myDir=new File("/sdcard/Pictures");
myDir.mkdirs();
String fname = "Image-"+ n +".jpg";
// filename = sdf.format(date);
File file = new File(myDir, fname);
if (file.exists ()) file.delete ();
try {
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
Toast.makeText(getApplicationContext(),"Saved to Light Box",Toast.LENGTH_LONG).show();
// 5
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Related
I am using ACTION_IMAGE_CAPTURE to capture image using camera. It works fine, But the problem is that image is showing in imageview after clicking but can not saved in external or internal storage. Here is my code for saving image in external storage.
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
File file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() + "/DashBoard/");
file.mkdirs();
ticket = Environment.getExternalStorageDirectory().getAbsolutePath() + "/DashBoard/Ticket.jpg";
file4 = new File(file, ticket);
try {
FileOutputStream out = new FileOutputStream(file4);
bitmap.compress(Bitmap.CompressFormat.JPEG , 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
ivTicket.setImageBitmap(bitmap);
Any solution ?
Use ImageWorker Library for easily saving bitmaps/drawables/base64.
How to Save
ImageWorker.to(context).
directory("ImageWorker").
subDirectory("SubDirectory").
setFileName("Image").
withExtension(Extension.PNG).
save(sourceBitmap,85)
Easy as that. Contributions are welcomed.
Follow it -
private void SaveImage(Bitmap finalBitmap) {
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);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
and add this in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
EDIT: By using this line you will be able to see saved images in the gallery view.
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
Reference
Try This:
private void SaveImage(Bitmap finalBitmap) {
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);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
and add this in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
another example here
UPDATE
instead of Environment.getExternalStorageDirectory() you can use your storage location as API level 30 and above Storage-policy is changed.
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" />
I am trying to save bitmap as .Jpg in storage. It saved successfully with this method .
private void SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/Dir");
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();
}
}
But saved Image orientation is 90 degree clockwised. I want to save it with original orientation. How can I solve this. Please kindly suggest me. Thank you.
You may try this.
First get the Exif data of the original image
ExifInterface originalImageExif = new ExifInterface(origFile.getAbsolutePath());
String origImageOrientation = originalImageExif.getAttribute(ExifInterface.TAG_ORIENTATION);
Then create new Exif data for the new image.
ExifInterface exifForNewImage = new ExifInterface(newFile.getAbsolutePath());
//Pass the origImageOrientation value that you get from the original image
exifForNewImage.setAttribute(ExifInterface.TAG_ORIENTATION, exifOrientation);
//Then save the Exif attributes
exifForNewImage.saveAttributes();
I hope this will help you.
Bitmap asd = Your bitmap image;
boolean deleted = false;
try
{//You can delete here
File file = new File("/sdcard/test.png");
deleted = file.delete();
}
catch (Exception e)
{
}
OutputStream stream = null;
try {
stream = new FileOutputStream("/sdcard/test.png");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
asd.compress(Bitmap.CompressFormat.PNG, 100, stream);
I'm implementing a save function to save a custom drawable view as an image. The problem is that the JPG image is created but it does not contain anything and finally the program "stops working unfortunately " Can anyone help me please here is my code;
Bitmap b = drawView.getDrawingCache();
File storage =Environment.getExternalStorageDirectory();
File file = new File(storage,spinner.getSelectedItem().toString()+".jpg");
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
b.compress(CompressFormat.JPEG, 95,fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
drawView.destroyDrawingCache();
use this one
private void SaveIamge(Bitmap finalBitmap) {
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);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
and add this in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I want that If my app start first time it should download image from web and store that image in Device/Emulator, from Device/Emulator that should be displayed in ImageView.
I have tried in this way :
ImageView myImgView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myImgView = (ImageView) findViewById(R.id.imageView1);
new MyAsnyc();
Log.d(MY_TAGT, "AsyncTask Executed.....");
}
private class MyAsnyc extends AsyncTask<Void, Void,Void>{
public File file ;
InputStream is;
private Bitmap bitmap;
protected void doInBackground() throws IOException{
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
file = new File(path, "DemoPicture.jpg");
try{
// Make sure the Pictures directory exists.
path.mkdirs();
URL url = new URL(BASE_URL);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
is = ucon.getInputStream();
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
Log.i(MY_TAGT, "Picture is readable........");
os.write(data);
Log.i(MY_TAGT, "Picture is Saved........");
is.close();
os.close();
}
catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
doInBackground();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(){
try{
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(null,
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
}
catch (Exception e) {
// TODO: handle exception
}
/*Here I want to set this image in ImageView*/
bitmap = BitmapFactory.decodeFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString()+"/DemoPicture.jpg");
myImgView.setImageBitmap(bitmap);
}
}
But in this way MyAsync class is not executed, please tell how to do that.
EDIT this is my log
Use execute to call it.
new MyAsnyc().execute();
use
new MyAsnyc().execute();
instead of
new MyAsnyc();
because AsyncTask.execute(Params... params) method used for executing an AsyncTask
EDIT :
use While or for loop for writing data in file as :
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
Log.i(MY_TAGT, "Picture is readable........");
int count;
while ( (count = is.read(data)) >= 0 ) {
os.write(data,0,count)
}
Log.i(MY_TAGT, "Picture is Saved........");
is.close();
os.close();
You must try this :
public class DownloadImage {
public static File getImage(String imageUrl, String fileName){
File file = null;
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
URL url = new URL(imageUrl);
Log.d("INFORMATION..", "FILE FOUNDED....");
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
Log.d("INFORMATION..", "FILE CONECTED....");
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, specifying the path, and the filename
//which we want to save the file as.
file = new File(SDCardRoot, fileName);
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
Log.d("INFORMATION..", "WRINTING TO FILE DOWNLOADED...." + file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
Log.d("INFORMATION..", "FILE DOWNLOADED....");
//this is where you would do something to report the prgress, like this maybe
//updateProgress(downloadedSize, totalSize);
}
//close the output stream when done
fileOutput.close();
Log.d("INFORMATION..", "FILE DOWNLOADING COMPLETED....");
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
}
Call this DownloadImage.getImage(String imageUrl, String fileName) in MainActivity.java like this :
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
String url = "http://4.bp.blogspot.com/-8v_k_fOcfP8/UQIL4ufghBI/AAAAAAAAEDo/9ffRRTM9AnA/s1600/android-robog-alone.png";
String file = DownloadImage.getImage(url, "My Image.jpg").toString();
// Get file path on device and set it to imageView
Bitmap bitmap = BitmapFactory.decodeFile(file);
imageView.setImageBitmap(bitmap);
}
}
I think this what you are looking for! hope this will help you
You forgot to execute the AsyncTask:
(new MyAsnyc()).execute();
Before line Log.d(MY_TAGT, "AsyncTask Executed.....");
you just construct new AsyncTask object but you didn't call execution on it with execute() method..
EDIT: second problem is that it is not so clear WHICH picture actually you want to display in that ImageView.. cause bitmap = BitmapFactory.decodeFile(..blahblahblah..) will probably be null after this.. It seems to me u r giving folder name and you wanted to decode that "file" to bitmap.. Make some logs about this decoding and bitmap value and show us..
Edit2:
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File file = new File(path, "DemoPicture.jpg");
bitmap = BitmapFactory.decodeFile(file);
should work a bit better..