i am building a chat application using firebase. I am using Glide to display images
Glide.with(getApplicationContext())
.load(imageUrl)
.crossFade()
.fitCenter()
.placeholder(R.drawable.loading)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imageView);
I want to save the images to a specific folder in Internal Storage just like whatsapp does and load images from there after it has been saved.Images are uploaded on Firebase Storage and its URL is saved in Firebase Database and i load them in a imageView with the url using Glide
private static final String IMAGE_DIRECTORY = "/yourfoldername/images";
//this method return your folder image path
public String saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File wallpaperDirectory = new File(
Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
// have the object build the directory structure, if needed.
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
try {
File f = new File(wallpaperDirectory, Calendar.getInstance().getTimeInMillis() + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(this,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
// glide load image
Glide.with(this)
.load(imageUrl)
.asBitmap()
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
String imagepath = saveImage(resource);
// Parse the gallery image url to uri
Uri savedImageURI = Uri.parse(imagepath);
// Display the saved image to ImageView
iv_saved.setImageURI(savedImageURI);
}
});
Related
Are there any Android libraries to resize images and save it in place? I'm using Jetpack Compose and Kotlin in my project. My app has a feature for taking photos and choosing an image from the gallery. And I need to resize the captured or selected image and create their thumbnails. I looked into Picasso, and Glide, etc. But, it seems like they only resize the image in memory for display.
HI You can use Glide for resize,
but again you can use it to save as image too
for eg use this to store in bitmap,
Glide.with(getApplicationContext())
.load("https://i.stack.imgur.com/quwoe.jpg")
.asBitmap()
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
saveImage(resource);
}
});
//code to save the image
private void saveImage(Bitmap resource) {
String savedImagePath = null;
String imageFileName = "image" + ".jpg";
final File storageDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
"/Pics");
boolean success = true;
if(!storageDir.exists()){
success = storageDir.mkdirs();
}
if(success){
File imageFile = new File(storageDir, imageFileName);
savedImagePath = imageFile.getAbsolutePath();
try {
OutputStream fOut = new FileOutputStream(imageFile);
resource.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
// Add the image to the system gallery
galleryAddPic(savedImagePath);
Toast.makeText(this, "IMAGE SAVED", Toast.LENGTH_LONG).show();
}
}
// Add the image to the system gallery
private void galleryAddPic(String imagePath) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(imagePath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
}
Resize with glide
save with Glide
i have this code here and i want to compress drawable result how can i do that?
Glide.with(context)
.load(Urls.BASE_URI +items.get(holder.getAdapterPosition()).getUserPhotoUrl())
.apply(requestOptions
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true).dontAnimate().fitCenter().circleCrop().override(100,100)
)
.into(new SimpleTarget<Drawable>() {
#Override
public void onResourceReady(#NonNull Drawable resource, #Nullable Transition<? super Drawable> transition) {
holder.userPhoto.setImageDrawable(resource);
}
});
try this
then write this code to get the drawable bitmap then convert the bitmap to file
public void doTheJob(){
Bitmap bitmap= BitmapFactory.decodeResource(context.getResources(),
R.drawable.icon_resource);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
//you can create a new file name "test.jpg" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.jpg");
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
new Compressor(this).compressToFileAsFlowable(f)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(file -> getTheBitmapOfTheFile(file), throwable -> throwable.printStackTrace());
// remember close de FileOutput
fo.close();
}
public void getTheBitmapOfTheFile(File file){
Bitmap bitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
try {
bitmap = BitmapFactory.decodeStream(new FileInputStream(file), null, options);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
but please don't forget to the permission of reading and writing to external storage
I had uploaded the image on Firebase Storage successfully. I have the URI and using Glide, I'm able to show the image on an ImageView. I want to save this image on my SD card but I'm getting an exception
java.io.FileNotFoundException: No content provider:
https://firebasestorage.googleapis.com/..
In here:
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), myUri);
SaveImage(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
Here is my complete code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_pic);
Intent intent = getIntent();
String str = intent.getStringExtra("pic");
Uri myUri = Uri.parse(str);
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), myUri);
SaveImage(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
ImageView imageView = (ImageView)findViewById(R.id.displayPic);
Glide.with(getApplicationContext()).load(myUri)
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imageView);
}
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();
}
}
URI looks like this:
https://firebasestorage.googleapis.com/example.appspot.com/o/pics%2Fc8742c7e-8f59-4ba3-bf6f-12aadfdf4a.jpg?alt=media&token=9bsdf67d-f623-4bcf-95d7-5ed97ecf1a21
Using Glide Try this.
Bitmap bitmap= Glide.
with(this).
load(mDownloadUrl).
asBitmap().
into(100, 100). // Width and height
get();
SaveImage(bitmap);
where mDownloadUrl is your image URL.
Firebase Storage does not have a registered content resolver. The download Url you get is actually a plain vanilla https:// Url that you can feed into Glide.
You can also download this Url directly. Check out this question.
Just call downloadUri.toString() to get the download Url in string form.
I am developing an app in which I want to download image from URL. I need to download these images at once and stored it into internal storage. There are more than 200 images for downloading. Please tell me the best way to download these images at minimum time possible. If any third part library is available the please tell.
Consider using Picasso for your purpose. I'm using it in one of my project. To save image on external disk you can use following:
Picasso.with(mContext)
.load(ImageUrl)
.into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
try {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/yourDirectory");
if (!myDir.exists()) {
myDir.mkdirs();
}
String name = new Date().toString() + ".jpg";
myDir = new File(myDir, name);
FileOutputStream out = new FileOutputStream(myDir);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch(Exception e){
// some action
}
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
);
From here you can download this library.
You can download th image from an url like this:
URL url = new URL("http://www.yahoo.com/image_to_read.jpg");
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
And you may then want to save the image so do:
FileOutputStream fos = new FileOutputStream("C://borrowed_image.jpg");
fos.write(response);
fos.close();
BitmapDrawable bitmapDrawable = (BitmapDrawable) holder.post_image.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
MediaStore.Images.Media.insertImage(mContext.getContentResolver(), bitmap, "IMG_" + Calendar.getInstance().getTime(), null);
It is quite a simple job...
const actionDownloadImage = (urls) => {
urls.map((url) => {
const splitUrl = url.split("/");
const filename = splitUrl[splitUrl.length - 1];
fetch(url)
.then((response) => {
response.arrayBuffer().then(function (buffer) {
const url = window.URL.createObjectURL(new Blob([buffer]));
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", filename); //or any other extension
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
})
.catch((err) => {
console.log(err);
});
});
}
I am using ImageView in my android application here i show the images from webservice so i am using UrlImageViewHelper. i want to store this image into android Gallery files.
my images like:
String Images = dataExtra.get("images").toString();
System.out.println("image URL"+Images);
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(Images);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
i tried like this.. but its not working. Any one can help me how to store these Images into Android Gallery?
i got solution for this problem, Here my answer
private void saveImagesIntoGallery(){
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
// File sdCardDirectory = Environment.getExternalStorageDirectory();// its stores under sdcard not in a specific path
String sdCardDirectory = Environment.getExternalStorageDirectory().toString()+"/Pictures/";
String url = arrayForImages[i].toString();
String file = url.substring(url.lastIndexOf('/')+1);
System.out.println("PATH NAME"+sdCardDirectory);
File image = new File(sdCardDirectory, file);
boolean success = false;
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getApplicationContext(), "Image saved with success",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_LONG).show();
}
}
Are you sure that the gallery is the best place to store images of webservice?
If you wanted to save to internal storage:
public void saveBitmap(String name, Bitmap bitmap){
if(bitmap!=null && name!=null){
FileOutputStream fos;
if(bitmap!=null){
try {
fos = openFileOutput(name, Context.MODE_PRIVATE);
bitmap.compress(CompressFormat.JPEG, 90, fos);
} catch (FileNotFoundException e) {}
}
}
}
To gallery, i have not examples here. But search a little;)