in my android application,I want to save some photos uploaded from a server on my database and then reuse them later. I think I should save them in a binary format and save their links into the database. Is it the better solution? Can you give some code or an example? Thanks.
PS: now I only uploaded the image and display it directly using an ImageView but I want to make it available in my application when the user is offline.
for my experience the best way to do achieve this is savin my images from internet to the sdcard cause the file access is faster.
function to create my images directory in my sdcard...
public static File createDirectory(String directoryPath) throws IOException {
directoryPath = Environment.getExternalStorageDirectory().getAbsolutePath() + directoryPath;
File dir = new File(directoryPath);
if (dir.exists()) {
return dir;
}
if (dir.mkdirs()) {
return dir;
}
throw new IOException("Failed to create directory '" + directoryPath + "' for an unknown reason.");
}
example:: createDirectory("/jorgesys_images/");
I use this functions to save my images from internet to my own folder into the sdcard
private Bitmap ImageOperations(Context ctx, String url, String saveFilename) {
try {
String filepath=Environment.getExternalStorageDirectory().getAbsolutePath() + "/jorgesys_images/";
File cacheFile = new File(filepath + saveFilename);
cacheFile.deleteOnExit();
cacheFile.createNewFile();
FileOutputStream fos = new FileOutputStream(cacheFile);
InputStream is = (InputStream) this.fetch(url);
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bitmap = BitmapFactory.decodeStream(is);
bitmap.compress(CompressFormat.JPEG,80, fos);
fos.flush();
fos.close();
return bitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public Object fetch(String address) throws MalformedURLException,IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
you will use this Bitmpap into your imageView, and when you are offline you will get the images directly from your sdcard.
Related
I have images in my drawables folder. Activity opens them, I choose the needed images and click on button. They must be saved on my SD Card through ImageSavingTask class instance execution which extends AsyncTask.
Here is my onClick code:
#Override
public void onClick(View v) {
for (int i = 0; i < 26; i++)
if (checkBoxes[i].isChecked()) {
imageIndex = new ImageIndex(); //ImageIndex-a class with single index field which reserves the checked checkbox indexes.
imageIndex.index = i;
Bitmap bitmap = ((BitmapDrawable) (images[i].getDrawable())).getBitmap();
SaveImageTask saveImageTask = new SaveImageTask();
saveImageTask.execute(bitmap); //The class SaveImageTask extends AsyncTask<Bitmap, Void, Void>
}
}
Then the selected images are handled in doInBackground method.
#Override
protected Void doInBackground(Bitmap... params) {
FileOutputStream outStream = null;
try {
Bitmap bitmap = params[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageBytes = stream.toByteArray();
File sdCard = Environment.getExternalStorageDirectory();
Drawable drawable = new BitmapDrawable(getResources(), bitmap);
File dir = new File(sdCard.getAbsolutePath());
dir.mkdirs();
String fileName = "Saved image " + imageIndex.index; //The reserved index of checkbox creates a name for the new file.
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
outStream.write(imageBytes);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
The <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> line is added in my manifest.
After I connect the USB to my phone, no error happens, but no images are saved to my SD Card. And I can't find images on my phone using windows search. Debugging doesn't give any answer. What kind of problem this could be?
It seems you have not asked runtime permissions for writing file on SD Card. From Android M and above you need to ask write permission at runtime to save any file on external sd card.
Check this link on how to request runtime permissions- https://developer.android.com/training/permissions/requesting.html
Also you can use google library - https://github.com/googlesamples/easypermissions
to request permissions.
I add the selected indexes into 2 ArrayLists of indexes and bitmaps. In the doInBackground method I created a loop.
For appearing the images on the card immediately I used the MediaScannerConnection.scanFile method.
for (int i = 0; i < 26; i++)
if (checkBoxes[i].isChecked()) {
index.add(i);
bitmap.add(bitmaps[i]);
}
if (bitmap.size() > 0)
new SaveImageTask().execute();
The doInBackground method:
protected Void doInBackground(Void... params) {
for (int i = 0; i < bitmap.size(); i++) {
try {
fname = "Saved image " + (index.get(i)) + ".jpg";
file = new File(myDir, fname);
if (file.exists()) file.delete();
FileOutputStream out = new FileOutputStream(file);
bitmap.get(i).compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
MediaScannerConnection.
scanFile(getApplicationContext(), new String[]{file.getPath()}, new String[]{"image/jpeg"}, null);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
I left the ImageSavingTask without fields and parameters.
I think problem where you try to write bytes.
Use Following Solution..
#Override
protected Void doInBackground(Bitmap... params) {
Bitmap bitmap = params[0];
saveToInternalStorage(bitmap, "MyImage"); // pass bitmap and ImageName
return null;
}
//Method to save Image in InternalStorage
private void saveToInternalStorage(Bitmap bitmapImage, String imageName) {
File mypath = new File(Environment.getExternalStorageDirectory(), imageName + ".jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.JPEG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
NOTE : Make sure you have added storage read/write permission and don't forget to ask permission on Marshmallow and higher version.
I am working in android studio. Building an app in which i am using a camera. When i run my app the app works fine. I capture the image it does captured the image. But the folder i created is not showing in my gallery. I am saving images in my local storage and not in SD CARD. I was very curious that why the folder is not created as it doesn't gives me any error so it should be in my gallery. So i restarted my device and after restarting i can see the folder in my gallery and the images taken in it. I again open the app and took images from it but again the images were not shown in the folder.
Below is my code in which i am making ta directory for saving images
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
{
if(resultCode == Activity.RESULT_OK)
{
Bitmap bmp = (Bitmap)data.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
// convert byte array to Bitmap
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
if(isStoragePermissionGranted())
{
SaveImage(bitmap);
}
}
}
private void SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().getAbsolutePath().toString();
Log.v(LOG_TAG, root);
File myDir = new File(root + "/captured_images");
myDir.mkdirs();
Random generator = new Random();
int n = 1000;
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,100,out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Below is the picture of my debugging
**Note: **
As i am using native camera so the pictures are saved in the camera roll folder i.e. the default folder in my device. But the image saved there is not the compressed one, the compress image should be saved in my created folder.
I am stuck to it and don't know what to do.
Any help would be highly appreciated.
You need to invoke scanFile(Context context, String[] paths, String[] mimeTypes, MediaScannerConnection.OnScanCompletedListener callback) method of MediaScannerConnection.
MediaScannerConnection provides a way for applications to pass a newly created or downloaded media file to the media scanner service. This will update your folder with the newly saved media.
private void SaveImage(Bitmap finalBitmap) {
//....
if(!storageDir.exists()){
storageDir.mkdirs();
}
//...
file.createNewFile();
try {
MediaScannerConnection.scanFile(context, new String[] {file.getPath()} , new String[]{"image/*"}, null);
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG,100,out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
try this
private void saveBitmap(Bitmap bitmap) {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = timeStamp + ".jpg";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
final String fileLoc = storageDir.getAbsolutePath() + "/folderName/" + imageFileName;
File file = new File(fileLoc);
OutputStream os = null;
try {
os = new BufferedOutputStream(new FileOutputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
try {`enter code here`
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I have a task in which I want to get drawable GIF image path but i am not getting correct path I tried below code to set path.
int resId = R.drawable.temp;
String imagePath2 = "android.resource://"+getPackageName()+"/"+resId;
String imagePath2 = ("android.resource://my.package.name/drawable/temp.gif");
but It's not working it's not giving me correct image but when i tried to get path from SD Card with below code
String inputPath = Environment.getExternalStorageDirectory()+ "/temp.gif";
it's working.
So now I am trying to store gif images from drawable or assets from SD card or internal memory. I found below code to copy PNG or JPEG to SD card.
Bitmap bm = BitmapFactory.decodeResource( getResources(), R.drawable.ic_launcher);
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File file = new File(extStorageDirectory, "ic_launcher.PNG");
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
but not getting any way to copy GIF image.
Any suggestions welcome.
Indeed you will not get a path from such a resource id. Instead you can get an InputStream from such a resource and use that stream to read the contents and copy for instance to a real file or whatever.
InputStream is = getResources().openRawResource(R.drawable.temp);
The type of the file does not matter. And as soon as you have this 'copy file' working you can throw away the code for copying jpg and png as it uses an intermediate Bitmap which is a bad idea and will change the file content and you end up with a different file -size-.
I made below method for getting image path and it's working perfect.
int resId = R.drawable.temp;
public String getFilePath(int resId){
// AssetManager assetManager = getAssets();
String fileName = "emp.gif";
InputStream in = null;
OutputStream out = null;
File outFile = null;
try {
//in = assetManager.open(fileName);
in = getResources().openRawResource(resId);
outFile = new File(getExternalFilesDir(null), fileName);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + fileName, e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// NOOP
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// NOOP
}
}
}
return outFile.getAbsolutePath();
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
I currently save images that I download from the internet to disk. I want to be able to delete the images when the user closes the app. I want the images all saved in one folder so it will be easy to delete them. I did getActivity().getCacheDir().getAbsolutePath()+ File.separator + "newfoldername" to get a path to a folder. Not sure how to add the images into the folder.
public void saveImage(Context context, Bitmap b, String name_file, String path) {
FileOutputStream out;
try {
out = context.openFileOutput(name_file, Context.MODE_PRIVATE);
b.compress(Bitmap.CompressFormat.JPEG,90, out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public Bitmap getImageBitmap(Context context, String name) {
try {
FileInputStream fis = context.openFileInput(name);
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap b = BitmapFactory.decodeStream(fis,null, options);
b.getAllocationByteCount());
fis.close();
return b;
} catch (Exception e) {}
return null;
}
You shouldn't save the images on your cache folder as you can't rely on it as per the documentation. A better approach would be to store them on your SD Card. As per the documentation :
public abstract File getCacheDir()
Returns the absolute path to the application specific cache directory on the filesystem. These files will be ones that get deleted first when the device runs low on storage. There is no guarantee when these files will be deleted. Note: you should not rely on the system deleting these files for you; you should always have a reasonable maximum, such as 1 MB, for the amount of space you consume with cache files, and prune those files when exceeding that space.
FOR SAVING
private String saveToInternalSorage(Bitmap bitmapImage){
File directory = getApplicationContext().getDir("MY_IMAGE_FOLDER"
,Context.MODE_PRIVATE);
File mypath=new File(directory,"profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return directory.getAbsolutePath();
}
FOR READING
private void loadImageFromStorage(String path)
{
try {
File file = new File(path, "Image.jpg");
Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(file));
ImageView img = (ImageView)findViewById(R.id.my_imgView);
img.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
FOR DELETING :
String dir = getApplicationContext().getDir("MY_IMAGE_FOLDER"
,Context.MODE_PRIVATE);
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
new File(dir, children[i]).delete();
}
}
I have stored some images in res folder of my app. But the user can download this image to their sdcard using the download option. How can I copy the image in res folder to sdcard. Can anyone help me.
You can do something like this,
if (isSdPresent()) { // to check is sdcard mounted
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
Bitmap bbicon = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
String extStorageDirectory = Environment.getExternalStorageDirectory()+ File.separator + "FolderName";
File wallpaperDirectory = new File(extStorageDirectory);
wallpaperDirectory.mkdirs();
OutputStream outStream = null;
File file = new File(wallpaperDirectory,"icon.png");
//to get resource name getResources().getResourceEntryName(R.drawable.icon);
try {
outStream = new FileOutputStream(file);
bbicon.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
}
to check SDCard
public boolean isSdPresent() {
return android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED);
}
Maybe this could help you getting a stream from your image and posting it to the user to download...