How to set image as wallpaper programmatically? - java

I have been developing the application which need to set an image as wallpaper.
Code:
WallpaperManager m=WallpaperManager.getInstance(this);
String s=Environment.getExternalStorageDirectory().getAbsolutePath()+"/1.jpg";
File f=new File(s);
Log.e("exist", String.valueOf(f.exists()));
try {
InputStream is=new BufferedInputStream(new FileInputStream(s));
m.setBitmap(BitmapFactory.decodeFile(s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("File", e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("IO", e.getMessage());
}
Also I have added the following permission:
<uses-permission android:name="android.permission.SET_WALLPAPER" />
But it doesn't works; the file exists on sdcard. Where have I made a mistake?

Possibly, you run out of memory if your image is big. You can make sure of it by reading Logcat logs. If this is the case, try to adjust your picture to device size by somewhat like this:
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels << 1; // best wallpaper width is twice screen width
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, width, height);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap decodedSampleBitmap = BitmapFactory.decodeFile(path, options);
WallpaperManager wm = WallpaperManager.getInstance(this);
try {
wm.setBitmap(decodedSampleBitmap);
} catch (IOException e) {
Log.e(TAG, "Cannot set image as wallpaper", e);
}

File f = new File(Environment.getExternalStorageDirectory(), "1.jpg");
String path = f.getAbsolutePath();
File f1 = new File(path);
if(f1.exists()) {
Bitmap bmp = BitmapFactory.decodeFile(path);
BitmapDrawable bitmapDrawable = new BitmapDrawable(bmp);
WallpaperManager m=WallpaperManager.getInstance(this);
try {
m.setBitmap(bmp);
} catch (IOException e) {
e.printStackTrace();
}
}
Open Androidmanifest.xml file and add permission like..
<uses-permission android:name="android.permission.SET_WALLPAPER" />
Try this and let me know what happen..

Related

Saving Image from an Image-View to device

I have two Image-View in a layout, one as at background and another is above that(at foreground) and I want to save both the images. So can anyone help me out that how can I save both the images into the device storage as single image.
Thank you.
A simple solution I found here is to put both of your imageView in a single Layout and then save your layout as a Bitmap. I will retype the solution code here
private Bitmap getBitmap(View v) {
v.clearFocus();
v.setPressed(false);
boolean willNotCache = v.willNotCacheDrawing();
v.setWillNotCacheDrawing(false);
// Reset the drawing cache background color to fully transparent
// for the duration of this operation
int color = v.getDrawingCacheBackgroundColor();
v.setDrawingCacheBackgroundColor(0);
if (color != 0) {
v.destroyDrawingCache();
}
v.buildDrawingCache();
Bitmap cacheBitmap = v.getDrawingCache();
if (cacheBitmap == null) {
Toast.makeText(StopWarApp.getContext(), "Something went wrong",
Toast.LENGTH_SHORT).show();
return null;
}
Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
// Restore the view
v.destroyDrawingCache();
v.setWillNotCacheDrawing(willNotCache);
v.setDrawingCacheBackgroundColor(color);
return bitmap;
}
Now that you have your Bitmap, you can save it to your storage like this
private void saveImage(Bitmap finalBitmap, String image_name) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root);
myDir.mkdirs();
String fname = "Image-" + image_name+ ".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();
}
}
Don't forget to add your permissions in the manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Share intent takes long time to appear

I'm trying to include image sharing in my application and everything is working but the share chooser takes long time to appear on devices
here is what i'm doing:
I have ImageView "items_details_image" and I want to share its image to be able to send it through whatsapp and other apps
void ShareImg() {
try {
Uri bmpUri = getLocalBitmapUri(items_details_image);
if (bmpUri != null) {
// Construct a ShareIntent with link to image
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/*");
// Launch sharing dialog for image
startActivity(Intent.createChooser(shareIntent, "Share Image"));
} else {
// ...sharing failed, handle error
}
} catch (Exception e) {
}
}
here is how I get bitmap from Image URL
public Uri getLocalBitmapUri(ImageView imageView) {
// Extract Bitmap from ImageView drawable
Drawable drawable = imageView.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable){
bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
return null;
}
// Store image to default external storage directory
Uri bmpUri = null;
try {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
I don't know why it is taking longer than usual comparing it with other apps on the same device such as gallery or whatever
You are doing disk I/O on the main application thread, in getLocalBitmapUri(). This will freeze your UI as long as it takes to write your bitmap to disk.

How to download image in android?

I have an image to the right and a button "download" to the left. the image is from my drawable. now,when i try to click the download i want to put the image to my sdcard downloads. Please help me i only see about download in url. is there other solution for this . Thanks
public class ImageDownloader {
public void download(String url, ImageView imageView) {
BitmapDownloaderTask task = new BitmapDownloaderTask(imageView);
task.execute(url);
}
}
/* class BitmapDownloaderTask, see below */
}
First, you need to get your Bitmap. You can already have it as an object Bitmap, or you can try to get it from the ImageView such as:
BitmapDrawable drawable = (BitmapDrawable) ImageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
Then you must get to directory (a File object) from SD Card such as:
File sdCardDirectory = Environment.getExternalStorageDirectory();
Next, create your specific file for image storage:
File image = new File(sdCardDirectory, "test.png");
After that, you just have to write the Bitmap such as:
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();
}
Finally, just deal with the boolean result if needed. Such as:
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();
}
Don't forget to add the following permission in your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

android_Get pictures from SDcard

Get pictures ​​path from SDcard.
My picture name is 01.jpg.
Make sure the picture is inside the SD card.
public boolean fileIsExists(){
try{
File f1 = new File("/sdcard/01.jpg");
f1 = new File("01.jpg");
if(!f1.exists()){
return true;
}
}catch (Exception e) {
// TODO: handle exception
return false;
}
return true;
}
boolean file1 = fileIsExists();
If picture is inside the SD card,then put picture into imageview.
Error is in the following code
if (file1==true){
imageView = (ImageView)findViewById(R.id.image_view);
String myJpgPath = "/sdcard/01.jpg";
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 0;
Bitmap bitmap = BitmapFactory.decodeFile(myJpgPath, options);//error here Cellphone can't run
imageView.setImageBitmap(bitmap);
}
Just try Following Code.
File f = new File("/mnt/sdcard/01.jpg");
ImageView mImgView1 = (ImageView)findViewById(R.id.imageView);
Bitmap bmp = BitmapFactory.decodeFile(f.getAbsolutePath());
mImgView1.setImageBitmap(bmp);
set your path like this:
String myJpgPath = Environment.getExternalStorageDirectory().getAbsolutePath()+"folderName/01.jpg";
Change +"sdcard/01.jpg"; to +"/01.jpg";
(And make sure Bitmap bitmap isn't repeat the local variables.)
if (file1==true){
String myJpgPath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/01.jpg";
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 0;
Bitmap bitmap = BitmapFactory.decodeFile(myJpgPath, options);
imageView.setImageBitmap(bitmap);
}

Android: how to create a BitmapDrawable from a file in the file system?

So I'm trying to restore an image from a file in my app's private files directory.
InputStream inputStream;
BitMapDrawable result;
try {
inputStream = new FileInputStream(file.getAbsolutePath());
result = BitmapDrawable.createFromStream(inputStream, null);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return result;
But obviously I'm doing something wrong because result is always null.
new BitmapDrawable( BitmapFactory.decodeFile(file.getAbsolutePath()) );
Isn't It what you want?
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
Drawable d = new BitmapDrawable(getResources(),bitmap);
imageview.setImageDrawable(d);

Categories