I'm showing images in my app and I want to add download button after every images when user click on it, image will automatically save to folder. Is it possible?
If you already have the file saved in your application, copy it to this public folder
File imagePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
Then use the technique provided here to scan the picture into the Gallery. Now when the user opens the Gallery they'll see the picture.
I tried Universal Image Loader And Picasso before.
you see that you need and witch one is enough to you.
also to have better decision read this one and this one.
it may help you :
you can use Glide for download image and i think it is better then picasso because it extends picasso.and for more information please see https://github.com/bumptech/glide.
for this you just have to include compile 'com.github.bumptech.glide:glide:3.6.1' into dependencies and then simply add this code line
Glide.with(this).load("http://goo.gl/gEgYUd").into(imageView);`
where http://goo.gl/gEgYUd is URL to pass.and after using this you have not to maintain cache.
enjoy your code:)
private static void persistImage(Bitmap bitmap, String name) {
File filesDir = getAppContext().getFilesDir();
File imageFile = new File(filesDir, name + ".jpg");
OutputStream os;
try {
os = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.flush();
os.close();
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
}
}
You can use Picasso library to display images. Add this below code in your build.gradle dependencies:
compile 'com.squareup.picasso:picasso:2.4.0'
Now use this to display images,You can add this code inside the onClick() method of your button.
File file = new File(imagePath);
if(file.exists()) {
Picasso.with(context).load(file).skipMemoryCache().placeholder(R.drawable.placeholder).into(yourImageView);
}
else {
Picasso.with(context).load(imageUrl).skipMemoryCache().placeholder(R.drawable.placeholder).into(yourImageView, new PicassoCallBack(yourImageView,imagePath));
}
The picassoCallBack class will look like this :
public class PicassoCallBack extends Callback.EmptyCallback {
ImageView imageView;
String filename;
public PicassoCallBack(ImageView imageView, String filename) {
this.imageView = imageView;
this.filename = filename;
}
#Override public void onSuccess() {
// Log.e("picasso", "success");
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
try {
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos1);
// FileOutputStream outStream = context.openFileOutput(filename, Context.MODE_PRIVATE);
File file = new File(filename);
FileOutputStream outStream = new FileOutputStream(file);
outStream.write(baos1.toByteArray());
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onError() {
Log.e("picasso", "error");
}
}
Hope it will do your job.
Related
I want to load an image from a file path which I have already defined, but don't want to instantiate another file object since I have already defined the path when saving the image.
I have tried retrieving the image with:
Picasso.with(this).load(filename).into(image_tv);
This is my code for saving the image;
Bitmap bitMapImg;
void saveImage() {
File filename;
try {
String path =
Environment.getExternalStorageDirectory().toString();
new File(path + "/folder/subfolder").mkdirs();
filename = new
File(path+"/folder/subfolder/image.jpg");
FileOutputStream out = new FileOutputStream(filename);
bitMapImg.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Use this
Picasso.with(context).load(Uri.parse("file://" + yourFilePath).into(imageView);
Ok i'm completely editing this post... I have made it so that I can save the file path to my data base. this works and is saved as /storage/emulated/0/1508blah blah.jpg . Now i cannot get my code to read this item back into a picture.
imagePhoto = (ImageView)findViewById(R.id.detail_recipe_image);
Toast.makeText(this, recipe.image, Toast.LENGTH_SHORT).show();
Bitmap bmp = BitmapFactory.decodeFile(String.valueOf(recipe.image));
imagePhoto.setImageBitmap(bmp);
am I missing something here? cause the Toast Is reading the recipe.image just fine and is displaying the path. why Is the rest not displaying the image?
Storage Code
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
String picturePath = destination.toString();
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
textImagePath.setText(picturePath.toString());
ImageView img = (ImageView)findViewById(R.id.addphotoview);
img.setImageBitmap(thumbnail);
}
Adding in the files paths seem to be the best solution to the problem i am having so that you #ModularSynth for your help with this. Always making sure all the info is your code to make the file paths work helps.
The idea of my app is to capture image from camera then crop specified area from it.
The problem :
When i save the cropped image in my sd card for the first time to launch the app, it saved properly. but when run my app one more time and take image then crop it. when save it the first image that take and crop at first time appear in the sd card not the current one.
This is my code for save images:
public static void save(Activity activity, Bitmap bm, String name) {
OutputStream outStream = null;
File externalFilesDir = activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File outFile = new File(externalFilesDir, "IDOCR" + File.separator + "Numbers");
if (!outFile.exists())
outFile.mkdirs();
File number = new File(outFile, name + ".PNG");
//if (number.exists())
// number.delete();
try {
//outStream = new FileOutputStream(new File(path));
outStream = new FileOutputStream(number);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
bm.recycle();
System.gc();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Maybe if you are trying to overwrite the previous version of the file, you should first delete the previous one...
You can add:
if (!outFile.exists())
outFile.mkdirs();
else {
outFile.delete();
outFile.createNewFile();
}
I have two buttons and a mapView. I want to save the MapView's view when I press one of the buttons.
Anyone got any idea about how I can do this?
You have to add a listener to the button (you should know how this done) and in that listener, do something like that:
boolean enabled = mMapView.isDrawingCacheEnabled();
mMapView.setDrawingCacheEnabled(true);
Bitmap bm = mMapView.getDrawingCache();
/* now you've got the bitmap - go save it */
File path = Environment.getExternalStorageDirectory();
path = new File(path, "Pictures");
path.mkdirs(); // make sure the Pictures folder exists.
File file = new File(path, "filename.png");
BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(file));
boolean success = bm.compress(CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
mMapView.setDrawingCacheEnabled(enabled); // reset to original value
In order to have the image show up in the Gallery immediately, you have to notify the MediaScanner about the new image like so:
if (success) {
MediaScannerClientProxy client = new MediaScannerClientProxy(file.getAbsolutePath(), "image/png");
MediaScannerConnection msc = new MediaScannerConnection(this, client);
client.mConnection = msc;
msc.connect();
}
google map have a function to take a snapshot so use this here is example, it return a bitmap that you can set on a image view its simple..
Bitmap bitmapMapsattelite ;
map.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
// Make a snapshot when map's done loading
map.snapshot(new GoogleMap.SnapshotReadyCallback() {
#Override
public void onSnapshotReady(Bitmap bitmap) {
bitmapMapsattelite = null;
/// make the bitmap null so everytime it //will fetch the new bitmap
bitmapMapsattelite = bitmap;
}
});
}
});
I used in this way to take only fragment screen using OSMDroid.
private void captureScreen() {
// put captureScreen() inside your OSMDroid fragment
// it's better put a button inside your layout OSMDroid fragment.xml
view = view.findViewById(R.id.mapview); //using OSMDroid fragment to call <org.osmdroid.views.MapView/>
view.setDrawingCacheEnabled(true);
Bitmap bmp = Bitmap.createBitmap(view.getDrawingCache());
//build your folder
File sd = new File(Environment.getExternalStorageDirectory() + "/ArqueoMaquina");
if (!sd.exists()) {
sd.mkdir();
}
File imagePath = new File(sd , "mapa" + System.currentTimeMillis() + ".png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
Uri uri = Uri.fromFile(imagePath); //to take the file path to your .png map saved in your phone
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
Those are the results. My screen App with OSMDroid fragment and Button "Save Map":
And my map.png saved in folder phone showing only the OSMDroid fragment:
The required functionality was introduced in Osmdroid 6.1.0. The corresponding class is MapSnapshot.
For the use case in the question adding the below code in the click callback of the button would work.
final MapSnapshot mapSnapshot = new MapSnapshot(new MapSnapshot.MapSnapshotable() {
#Override
public void callback(final MapSnapshot pMapSnapshot) {
if (pMapSnapshot.getStatus() != MapSnapshot.Status.CANVAS_OK) {
return;
}
final Bitmap bitmap = Bitmap.createBitmap(pMapSnapshot.getBitmap());
// Do something with the bitmap like save to file
}
}, MapSnapshot.INCLUDE_FLAG_UPTODATE, pMapView);
new Thread(mapSnapshot).start();
Reference : https://github.com/osmdroid/osmdroid/issues/1737
Google map has a call back named snapshot -> map.snapshot that return a Bitmap to handling.
In osmdroid (open street map android api), corresponding method is getDrawingCache method -> map.getDrawingCache
I am developing an application for Android, and part of the application has to takes pictures and save them to the SDcard. The onPictureTaken method returned a byte array with the data of the captured image.
All I need to do is save the byte array into a .jpeg image file. I have attempted to do this with the help of BitmapFactory.decodeByteArray (to get a Bitmap) and then bImage.compress (to an OutputStream), a plain OutputStream, and a BufferedOutputStream. All three of these methods seem to give me the same weird bug. My Android phone (8MP camera and a decent processor), seems to save the photo (size looks correct), but in a corrupted way (the image is sliced and each slice is shifted; or I just get almost horizontal lines of various colors); and The weird thing is, that an Android tablet with a 5MP camera and a fast processor, seems to save the image correctly.
So I thought maybe the processor can't keep up with saving large images, because I got OutOfMemory Exceptions after about 3 pictures (even at compression quality of 40). But then how does the built in Camera app do it, and much faster too? I'm pretty sure (from debug) that the OutputStream writes all the data (bytes) and it should be fine, but it's still corrupted.
***In short, what is the best/fastest way (that works) to save a byte array to a jpeg file?
Thanks in advance,
Mark
code I've tried (and some other slight variations):
try {
Bitmap image = BitmapFactory.decodeByteArray(args, 0, args.length);
OutputStream fOut = new FileOutputStream(externalStorageFile);
long time = System.currentTimeMillis();
image.compress(Bitmap.CompressFormat.JPEG,
jpegQuality, fOut);
System.out.println(System.currentTimeMillis() - time);
fOut.flush();
fOut.close();
} catch (Exception e) {
}
and
try {
externalStorageFile.createNewFile();
FileOutputStream fos = new FileOutputStream(externalStorageFile);
fos.write(args);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
All I need to do is save the byte array into a .jpeg image file.
Just write it out to a file. It already is in JPEG format. Here is a sample application demonstrating this. Here is the key piece of code:
class SavePhotoTask extends AsyncTask<byte[], String, String> {
#Override
protected String doInBackground(byte[]... jpeg) {
File photo=new File(Environment.getExternalStorageDirectory(), "photo.jpg");
if (photo.exists()) {
photo.delete();
}
try {
FileOutputStream fos=new FileOutputStream(photo.getPath());
fos.write(jpeg[0]);
fos.close();
}
catch (java.io.IOException e) {
Log.e("PictureDemo", "Exception in photoCallback", e);
}
return(null);
}
}
Hey this codes for kotlin
camera.addCameraListener(object : CameraListener(){
override fun onPictureTaken(result: PictureResult) {
val jpeg = result.data //result.data is a ByteArray!
val photo = File(Environment.getExternalStorageDirectory(), "/DCIM/androidify.jpg");
if (photo.exists()) {
photo.delete();
}
try {
val fos = FileOutputStream(photo.getPath() );
fos.write(jpeg);
fos.close();
}
catch (e: IOException) {
Log.e("PictureDemo", "Exception in photoCallback", e)
}
}
})
This Code is perfect for saving image in storage, from byte[]...
note that "image" here is byte[]....taken as "byte[] image" as a parameter into a function.
File photo=new File(Environment.getExternalStorageDirectory(), "photo.jpg");
if (photo.exists()) {
photo.delete();
}
try {
FileOutputStream fos=new FileOutputStream(photo.getPath());
Toast.makeText(this, photo.getPath(), Toast.LENGTH_SHORT).show();
fos.write(image);
fos.close();
}
catch (java.io.IOException e) {
Log.e("PictureDemo", "Exception in photoCallback", e);
}
}
Here's the function to convert byte[] into image.jpg
public void SavePhotoTask(byte [] jpeg){
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "Life Lapse");
imagesFolder.mkdirs();
final File photo= new File(imagesFolder, "name.jpg");
try
{
FileOutputStream fos=new FileOutputStream(photo.getPath());
fos.write(jpeg);
fos.close();
}
catch(Exception e)
{
}
}