I am using a Glide library for loading remote URLs into ImageView's.
I want to save the image from this ImageView to gallery. (I don't want to make another network call again to download the same image).
How we can achieve this?
Glide.with(yourApplicationContext))
.load(youUrl)
.asBitmap()
.into(new SimpleTarget<Bitmap>(myWidth, myHeight) {
#Override
public void onResourceReady(Bitmap bitmap, GlideAnimation anim) {
//set bitmap to imageview and save
}
};
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 200, 200, false);
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 60, byteArrayOutputStream);
String fileName = "image.jpeg";
File file = new File("your_directory_path/"
+ fileName);
try {
file.createNewFile();
// write the bytes in file
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(byteArrayOutputStream.toByteArray());
// remember close the FileOutput stream
fileOutputStream.close();
ToastHelper.show(getString(R.string.qr_code_save));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ToastHelper.show("Error");
}
Note : If your drawble is not always an instanceof BitmapDrawable
Bitmap bitmap;
if (mImageView.getDrawable() instanceof BitmapDrawable) {
bitmap = ((BitmapDrawable) mImageView.getDrawable()).getBitmap();
} else {
Drawable d = mImageView.getDrawable();
bitmap = Bitmap.createBitmap(d.getIntrinsicWidth(), d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
Try this
I haven't try this way. But i think this match your problem. Put this code on onBindViewHolder of your RecyclerView adapter.
Glide.with(yourApplicationContext))
.load(youUrl)
.asBitmap()
.into(new SimpleTarget<Bitmap>(myWidth, myHeight) {
#Override
public void onResourceReady(Bitmap bitmap, GlideAnimation anim) {
//Set bitmap to your ImageView
imageView.setImageBitmap(bitmap);
viewHolder.saveButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
//Save bitmap to gallery
saveToGallery(bitmap);
}
});
}
};
This might help you
public void saveBitmap(ImageView imageView) {
Bitmap bitmap = ((GlideBitmapDrawable) imageView.getDrawable()).getBitmap();
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/My 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);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception ex) {
//ignore
}
}
Related
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
In my app i want to capturea a part of my android application UI and save it programmatically .
For example i want do this actions :
In Activity/Fragment user clicks one Button .
capture from a part of Layout for example a LinearLayout that have id="captureMe" .
Save captured image somewhere .
how i can implement it ?
You can simply use this function just pass your view object
public Bitmap viewToBitmap(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
Then Save this file
public void saveImage(Bitmap inImage) {
String root = Environment.getExternalStorageDirectory().toString();
File mydir = new File(root + "/demo/");
mydir.mkdirs();
String fname = "Image.jpeg";
File file = new File (mydir, fname);
String path2=file.getPath();
Uri uri=Uri.fromFile(file);
try {
FileOutputStream out = new FileOutputStream(file);
inImage.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}catch (Exception e)
{
e.printStackTrace();
}
}
Try this, hope it works
LinearLayout captureMe = (LinearLayout)findViewById(R.id.captureMe);
captureMe.setDrawingCacheEnabled(true);
captureMe.buildDrawingCache();
bitmap = captureMe.getDrawingCache();
First Use this function to get bitmap of view that you want to capture:
public static Bitmap getViewBitmap(View v, int width, int height) {
Bitmap viewBitmap = Bitmap.createBitmap(width , height,
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(viewBitmap);
v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
v.draw(c);
return viewBitmap;
}
Then use this code to save this bitmap to storage:
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOutputStream = null;
File file = new File(path + "/Captures/", "screen.jpg");
try {
fOutputStream = new FileOutputStream(file);
capturedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOutputStream);
fOutputStream.flush();
fOutputStream.close();
MediaStore.Images.Media.insertImage(getContentResolver(),
file.getAbsolutePath(), file.getName(), file.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, "Save Failed", Toast.LENGTH_SHORT).show();
return;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Save Failed", Toast.LENGTH_SHORT).show();
return;
}
I have a loaded image on my imageview widget which was loaded from glide library. I want to use a share intent to share that image to other applications. I have tried various possibilities without any success. Please help.
public class BookstorePreviewActivity extends AppCompatActivity {
ImageView imageView;
LinearLayout mShare;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bookstore_preview);
imageView = findViewById(R.id.image_preview_books);
mShare= findViewById(R.id.download_books);
mShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// fetching image view item from cache
imageView.setDrawingCacheEnabled(true);
Bitmap bitmap = imageView.getDrawingCache();
File root = Environment.getExternalStorageDirectory();
File cachePath = new File(root.getAbsolutePath());
try {
cachePath.createNewFile();
FileOutputStream outputStream = new FileOutputStream(cachePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// sharing image to other applications (image not found)
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(cachePath));
startActivity(Intent.createChooser(share, "Share via"));
}
});
Just Pass activity context to the takeScreenShot activity it will
work!!!
public static Bitmap takeScreenShot(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap b1 = view.getDrawingCache();
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
//Find the screen dimensions to create bitmap in the same size.
DisplayMetrics dm = activity.getResources().getDisplayMetrics();
int width = dm.widthPixels;
int height = dm.heightPixels;
Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight);
view.destroyDrawingCache();
takeScreen(b,activity);
return b;
}
public static void takeScreen(Bitmap bitmap,Activity a) {
//Bitmap bitmap = ImageUtils.loadBitmapFromView(this, view); //get Bitmap from the view
String mPath = Environment.getExternalStorageDirectory() + File.separator + "tarunkonda" + System.currentTimeMillis() + ".jpeg";
File imageFile = new File(mPath);
try {
OutputStream fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
fout.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
openScreenshot(imageFile,a);
}
private static void openScreenshot(File imageFile,Activity activity) {
Intent intent = new Intent(activity,ImageDrawActivity.class);
intent.putExtra(ScreenShotActivity.PATH_INTENT_KEY,imageFile.getAbsolutePath());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
}
I am trying to make wallpaper fit to screen in above API 23, but somehow I am getting an error for bitmap drawable. Error is "android.graphics.drawable.TransitionDrawable cannot be cast to android.graphics.drawable.BitmapDrawable".
Same code I have for API 22 and it is working perfect. Help me out.
Here is my code.
case R.id.action_wallpaper:
progressBar.setVisibility(View.VISIBLE);
BitmapDrawable drawable1 = (BitmapDrawable) image.getDrawable();
temp = drawable1.getBitmap();
// Drawable d = image.getDrawable();
String s = "image";
// temp = ((BitmapDrawable)d).getBitmap();
FileOutputStream out =
null;
try {
out = openFileOutput(s, Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
temp.compress(Bitmap.CompressFormat.PNG, 90, out);
setWallpaper();
progressBar.setVisibility(View.GONE);
break;
void setWallpaper() {
BitmapDrawable drawable = (BitmapDrawable) image.getDrawable();
// Bitmap bitmap = drawable.getBitmap();
Bitmap icon = drawable.getBitmap();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
icon.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "wallpaper.jpg");
try {
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Wallpaper Set",
Toast.LENGTH_SHORT).show();
Thread th = new Thread() {
public void run() {
// temp = image.getDrawingCache();
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int height = metrics.heightPixels;
int width = metrics.widthPixels;
// Bitmap tempbitMap =
// BitmapFactory.decodeResource(getResources(), R.drawable.img);
Bitmap bitmap = Bitmap.createScaledBitmap(temp, width, height,
true);
WallpaperManager wallpaperManager = WallpaperManager
.getInstance(WallpaperActivity.this);
wallpaperManager.setWallpaperOffsetSteps(1, 1);
wallpaperManager.suggestDesiredDimensions(width, height);
try {
wallpaperManager.setBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
}
});
I'm trying to take a screenshot of the currently playing video. I'm trying with code that successfully takes a screenshot of web view but get not success in taking photo of currently playing video.
The code as follow for web view.
WebView w = new WebView(this);
w.setWebViewClient(new WebViewClient()
{
public void onPageFinished(WebView view, String url)
{
Picture picture = view.capturePicture();
Bitmap b = Bitmap.createBitmap( picture.getWidth(),
picture.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas( b );
picture.draw( c );
FileOutputStream fos = null;
try {
fos = new FileOutputStream( "/sdcard/yahoo_" +System.currentTimeMillis() + ".jpg" );
if ( fos != null )
{
b.compress(Bitmap.CompressFormat.JPEG, 90, fos );
fos.close();
}
} catch( Exception e )
{
//...
}
}
});
setContentView( w );
w.loadUrl( "http://www.yahoo.com");
To expand on 66CLSjY's answer, FFmpegMediaMetadataRetriever has the same interface as MediaMetadataRetriever but it uses FFmpeg as the backend. If the default configuration won't work with your video format you can enable/disable codecs by recompiling. Here is some sample code:
FFmpegMediaMetadataRetriever mmr = new FFmpegMediaMetadataRetriever();
mmr.setDataSource(mUri);
mmr.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_VIDEO_CODEC);
Bitmap b = getFrameAtTime(3000);
mmr.release();
try this it will gives bitmap for your app screen
View v = view.getRootView();
v.setDrawingCacheEnabled(true);
Bitmap b = v.getDrawingCache();
This works for me:
First a method to convert your view into a bitmap
public static Bitmap getBitmapFromView(View view) {
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(),view.getHeight(),Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
Drawable bgDrawable =view.getBackground();
if (bgDrawable!=null)
bgDrawable.draw(canvas);
else
canvas.drawColor(Color.WHITE);
view.draw(canvas);
return returnedBitmap;
}
Then save into the SD, for example:
static private boolean saveImage(Bitmap bm, String absolutePath)
{
FileOutputStream fos = null;
try
{
String absolutePath = "your path"
File file = new File(absolutePath);
fos = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, fos); //PNG ignora la calidad
} catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (fos != null)
fos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
return true;
}
Good Luck!