Set image loaded from URL as wallpaper - android

I'm using Picasso in my app and I managed to open the image in a fullscreen view when the user taps it. Now I would like a button which overlays the image and that sets the image as wallpaper.
All images are loaded from URL and stored in a remote server.
I don't know how to achieve this since I'm a veeeery beginner. Can someone help me?
Thanks.

Use this code in button onclicklistener to set image as wallpaper
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
WallpaperManager wpm = WallpaperManager.getInstance(getApplicationContext());
wpm.suggestDesiredDimensions(width, height);
InputStream ins = null;
try {
ins = new URL(Imageurl).openStream();
wpm.setStream(ins);
Toast.makeText(ImageViewerActivity.this, "successfully set", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}

use ImageLoader instead:
DisplayImageOptions options = new DisplayImageOptions.Builder()
.bitmapConfig(Bitmap.Config.ALPHA_8)
.imageScaleType(ImageScaleType.IN_SAMPLE_INT).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
ISolaceContext.getAppContext())
.discCacheExtraOptions(20, 20, CompressFormat.JPEG, 100, null)
.defaultDisplayImageOptions(Media.options).build();
ImageLoader.getInstance().init(config);
ImageLoader loader = ImageLoader.getInstance();
loader.loadImage(url, new SimpleImageLoadingListener() {
#Override
public void onLoadingComplete(String imageUri, View view,
Bitmap loadedImage) {
// Now you have the image in your hands as a Bitmap(called: loadedImage) and Now you can do whatever you want with it
stream.close();
stream = null;
}
});
loader.clearDiscCache();
loader.clearMemoryCache();
Now you can use the previously generated Bitmap as a background.converting bitmap to drawable.

Related

Android: Universal Image Loader - Add new image to cache

I am successfully integrate Universal Imageloader in my Gallery App to show the images from the phone storage
But new images (captured from the camera /processed images) stored in the app's specified folder doesn't appear in the gallery. even the application restarted.
May be due to this error
W/ImageLoader: Try to initialize ImageLoader which had already been initialized before. To re-init ImageLoader with new configuration call ImageLoader.destroy() at first.
I think add the details of new image to the cache will resolve the problem. but don't know how . please help
code : Activity Extends Application
DisplayImageOptions defaultDisplayImageOptions = new DisplayImageOptions.Builder() //
.considerExifParams(true)
.resetViewBeforeLoading(true)
.showImageOnLoading(R.drawable.nophotos)
.showImageOnFail(R.drawable.nophotos)
.delayBeforeLoading(0)
.build(); //
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
getApplicationContext())
.defaultDisplayImageOptions(defaultDisplayImageOptions)
.memoryCacheExtraOptions(480, 800).threadPoolSize(5)
.build();
ImageLoader.getInstance().init(config);
load all album
PhoneMediaControl mediaControl = new PhoneMediaControl();
mediaControl.setLoadalbumphoto(new loadAlbumPhoto() {
#Override
public void loadPhoto(ArrayList<AlbumEntry> albumsSorted_) {
albumsSorted = new ArrayList<PhoneMediaControl.AlbumEntry>(albumsSorted_);
if (mView != null && mView.getEmptyView() == null) {
mView.setEmptyView(null);
}
if (listAdapter != null) {
listAdapter.notifyDataSetChanged();
}
}
});
mediaControl.loadGalleryPhotosAlbums(mContext, 0);
is there any way to add new processed image to the cache or already initiated imageloader
You just have to load the your image with universal image loader it will automatically cache it.
Loading
ImageLoader imageLoader = ImageLoader.getInstance();
Uri uri = Uri.fromFile(new File("/DCIM/Camera/1470634175974.jpg"));
imageLoader.loadImage(uri.toString(), new SimpleImageLoadingListener() {
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
// Do whatever you want with Bitmap
}
});
UNIVERSAL IMAGE LOADER ACCEPTED URI schemes
"file:///mnt/sdcard/image.png" // from SD card
"file:///mnt/sdcard/video.mp4" // from SD card (video thumbnail)
"content://media/external/images/media/13" // from content provider
"content://media/external/video/media/13" // from content provider (video thumbnail)
"assets://image.png" // from assets
"drawable://" + R.drawable.img // from drawables (non-9patch images)
Initialize your UniversalImageLoader instance only once inside onCreate() of your Application class, not inside each Activity or elsewhere.
I found this will reslove the problem using the function loadImageSync();
ImageLoader.getInstance().loadImageSync(filepath);

Android Imageview fails to load

I'm fetching a single image for a single person. Everything goes well but if there is no image in the database I get an exception (my app crashes). I do handle this with a else statement but it doesn't seem to work.
Here is the code:
private void Get_Image_From_Database(DataBaseHelper db,String query)// GET_IMAGE
{
Bitmap bitmap=null;
SQLiteDatabase db1 = db.getReadableDatabase();
Cursor c=db1.rawQuery(query, null);
if (c != null) {
if (c.moveToFirst())
{
do
{
byte[] blob = c.getBlob(0);
ByteArrayInputStream inputStream = new ByteArrayInputStream(blob);
bitmap = BitmapFactory.decodeStream(inputStream);
img.setImageBitmap(bitmap); // if there is a image it will render one
} while (c.moveToNext());
}
else{File imgfile=new File("/drawable/none.jpg"); //the else statement fails
Bitmap mybitmap=BitmapFactory.decodeFile(imgfile.getAbsolutePath());
img.setImageBitmap(mybitmap);}
}
}
My goal is to (as you can see) get a image from a database if exits and if not, then display a default image.
I suppose the drawable is in your resource inside of your project?
If yes, try this to get your drawable:
Drawable myDrawable = getResources().getDrawable(R.drawable.none);
img.setImageDrawable(myDrawable);
for loading images you can use universal imageLoader, it will also hellp you to cache the images
and it has a beautiful option
ex
options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisc(true)
.showImageOnLoading(R.drawable.placeholder)
.showImageForEmptyUri(R.drawable.placeholder)
.showImageOnFail(R.drawable.placeholder)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
as you can see if you dont have any image to display to can display the default image
If that image is in Drawable folder then just change your else part to
else
{
img.setImageResource(R.drawable.none);
}
I guess else part is at wrong place.
EDIT
If you're using try-catch block, then you can do like this in catch block
catch (Exception e)
{
img.setImageResource(R.drawable.none);
}
This solved my problem!
Thanx guys especially aniruddha!!
private void Get_Image_From_Database(DataBaseHelper db,String query)// GET_IMAGE
{
SQLiteDatabase db1 = db.getReadableDatabase();
Cursor c=db1.rawQuery(query, null);
c.moveToFirst();
if (c.isNull(0))
{
img.setImageResource(R.drawable.none);
}
else
{
byte[] blob = c.getBlob(0);
ByteArrayInputStream inputStream = new ByteArrayInputStream(blob);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
img.setImageBitmap(bitmap); // if there is a image it will render one
}
}

How can i just download image with universal-image-loader

as far as I know, universal-image-loader provide 2 kinds of methods to display images. imageLoader.loadImage and imageLoader.displayImage. But those 2 methods must bind to UI element to display. Can I just download files for cache in a thread (for future display). I don't need to display those image right now.
You can still use UIL. Based on the displayOptions used below the images would be cached.
Refer here - https://github.com/nostra13/Android-Universal-Image-Loader
// Load image, decode it to Bitmap and return Bitmap to callback
imageLoader.loadImage(imageUri, displayOptions, new SimpleImageLoadingListener() {
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
// Do whatever you want with Bitmap
}
});
Can I just download files for cache in a thread (for future display).
I don't need to display those image right now.
You can download files using Executor or creating a thread. You don't need to use universal imageloader.
http://developer.android.com/reference/java/util/concurrent/Executor.html.
You can also use a DownloadManager and save the file in sdcard. You can retrieve the same for later use.
http://oodlestechnologies.com/blogs/Downloading-and-Retrieving-Files-on-SD-card-in-Android-using-Android-SDK-in-Eclipse
To cache bitmaps you can write the images to a folder in sdcard.
Caching bitmaps
http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html.
You cache bitmaps in memory or disk. The link has details regarding the topic.
You basically use UIL ofr displaying images in listview or grdiview. To use UIL in listview or gridview you can do as below.
https://github.com/nostra13/Android-Universal-Image-Loader. It is based on Lazy List(works on same principle). But it has lot of other configurations. You can display a error image if downlaod failed. Can display images with rounded corners. Can cache on disc or memory. Can compress image.
In your custom adapter constructor
File cacheDir = StorageUtils.getOwnCacheDirectory(a, "your folder");
// Get singletone instance of ImageLoader
imageLoader = ImageLoader.getInstance();
// Create configuration for ImageLoader (all options are optional)
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(a)
// You can pass your own memory cache implementation
.discCache(new UnlimitedDiscCache(cacheDir)) // You can pass your own disc cache implementation
.discCacheFileNameGenerator(new HashCodeFileNameGenerator())
.enableLogging()
.build();
// Initialize ImageLoader with created configuration. Do it once.
imageLoader.init(config);
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.stub_id)//display stub image
.cacheInMemory()
.cacheOnDisc()
.displayer(new RoundedBitmapDisplayer(20))
.build();
In your getView()
ImageView image=(ImageView)vi.findViewById(R.id.imageview);
imageLoader.displayImage(imageurl, image,options);//provide imageurl, imageview and options
You can configure with other options to suit your needs.
Along with lazy loading/Universal Image Loader you can view holder for smooth scrolling and performance. http://developer.android.com/training/improving-layouts/smooth-scrolling.html.
Theres loadImage(String uri, ImageLoadingListener listener), I think you can call it with null for the listener if you don't need one.
Adding to #Robin Srivastava's answer:
You must also instantiate the ImageLoader context, for example:
imageLoader = ImageLoader.getInstance(); before you can use the loadImage method. The displayOptions parameter is also optional so you can exclude that if need be.
Using UIL,we can save the image when the image is fully loaded.
using ImageLoading Listener when loading is completed the listener has a method called onLoadingComplete() we can get Bitmap of the image and we can store this Bitmap using the below method saveImage()
Bitmap imageBitmap=null;
ImageLoader.getInstance().displayImage(String.valueOf(mediaPath), imageView, options, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
String message = null;
switch (failReason.getType()) {
case UNKNOWN:
message = "Unknown error";
break;
case IO_ERROR:
message = "I/O error";
break;
case NETWORK_DENIED:
message = "Network Denied";
break;
case OUT_OF_MEMORY:
message = "Out of memory";
break;
case DECODING_ERROR:
message = "decoding error";
break;
}
Toast.makeText(FullScreenActivity.this, message, Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
//we can get imageBitmap here when loading is completed
imageBitmap=loadedImage;
progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
}
});
Use this method to save the file in your local storage
public void saveImage(){
if(imageBitmap!=null){
File dir = new File( Environment.getExternalStorageDirectory().getAbsolutePath() + “/Images/");
if (!dir.exists()) {
if (dir.mkdirs()) {
Log.i(TAG, "Directory created");
}
}
//put your image file name here
File mypath=new File(dir,"yourImageName.png");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
if(imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)){
showToast("Successfully downloaded");
}
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Toast toast=null;
private void showToast(String message) {
if (toast != null) toast.cancel();
toast = Toast.makeText(FullScreenActivity.this, message, Toast.LENGTH_SHORT);
toast.show();
}

How do I tell BitmapFactory.decodeStream to give me a full quality image?

So I have the following code in an AsyncTask. The AsyncTask takes in a url to an image file, downloads it into a Bitmap, saves the Bitmap off to disk somewhere, and then displays the Bitmap in an existing ImageView.
Here's the implementation of the doInBackground() call for my AsyncTask:
protected Bitmap doInBackground(String... urls) {
try {
URL image_url = new URL(urls[0]);
String image_url_prefix_regex = "http://www\\.somewebsite\\.com";
if (externalStorageIsAvailable()) {
String file_path = getExternalFilesDir(null).getPath() + image_url.toString().replaceAll(image_url_prefix_regex, "");
File target_file = new File(file_path);
if (!target_file.getParentFile().exists()) {
target_file.getParentFile().mkdirs();
}
BitmapFactory.Options bitmap_options = new BitmapFactory.Options();
bitmap_options.inScaled = false;
bitmap_options.inDither = false;
bitmap_options.inPreferredConfig = Bitmap.Config.ARGB_8888;
bitmap_options.inPreferQualityOverSpeed = true;
bitmap_options.inSampleSize = 1;
Bitmap image = BitmapFactory.decodeStream(image_url.openStream(), null, bitmap_options);
image.compress(CompressFormat.JPEG, 100, new FileOutputStream(target_file));
return image;
}
}
catch (MalformedURLException e) {
Log.v(DEBUG_TAG, "Error: Caught MalformedURLException");
}
catch (IOException e) {
Log.v(DEBUG_TAG, "Error: Caught IOException");
}
return null;
}
Then later in the onPostExecute() call I have this:
protected void onPostExecute(Bitmap image) {
ImageView mImageView = (ImageView) findViewById(R.id.main_image);
mImageView.setImageBitmap(image);
}
Yet when the code downloads and displays the image, the image is reduced in size and quality. How do I make it so that the resulting image is full quality? Those BitmapFactory.Options settings are the things I've tried thus far, but they did not seem to work.
Note that I'm not asking about the image that gets saved to external storage. I think that one will likely be of lower quality due to getting compressed again, but that shouldn't affect the image I'm sending to my ImageView, which is what I'm asking about. Of course, if there's anything wrong with these assumptions please point them out.
Why you are using Bitmap factory options while decoding bitmap Stream ?
Just use the
Bitmap image = BitmapFactory.decodeStream(image_url.openStream());
instead of
Bitmap image = BitmapFactory.decodeStream(image_url.openStream(), null, bitmap_options);

creating a drawable from sd card to set as a background in android

I am trying to use an image from the sd card and set it as the background for a relativelayout. I have tried other solutions that i have found here and elsewhere but they havent seemed to work for me. here is my code. I have commented out other ways that i have tried and didnt work. the only thing that worked for me was using setBackgroudnResource and using a resource from the app, but this was just to test to make sure mRoot was set up correctly. when I have tried all the other ways, it just doesn't set anything. Anyone know what I am doing wrong, or if there is a better way to do this?
//one way i tired...
//String extDir = Environment.getExternalStorageDirectory().toString();
//Drawable d = Drawable.createFromPath(extDir + "/pic.png");
//mRoot.setBackgroundDrawable(d);
//another way tried..
//Drawable d = Drawable.createFromPath("/sdcard/pic.png");
//mRoot.setBackgroundDrawable(d);
//last way i tried...
mRoot.setBackgroundDrawable(Drawable.createFromPath(new File(Environment.getExternalStorageDirectory(), "pic.png").getAbsolutePath()));
//worked, only to verify mRoot was setup correctly and it could be changed
//mRoot.setBackgroundResource(R.drawable.bkg);
You do not load a drawable from SD card but a bitmap. Here is a method to load it with the reduced sampling (quality) so the program will not complain if the image is too large. Then I guess you need to process this bitmap i.e. crop it and resize for the background.
// Read bitmap from Uri
public Bitmap readBitmap(Uri selectedImage) {
Bitmap bm = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2; //reduce quality
AssetFileDescriptor fileDescriptor =null;
try {
fileDescriptor = this.getContentResolver().openAssetFileDescriptor(selectedImage,"r");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
finally{
try {
bm = BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options);
fileDescriptor.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return bm;
}
The Uri here can be supplied from a gallery picker activity.
The image then can be saved into application resources and loaded into an imageView
private void saveBackground(Bitmap Background) {
String strBackgroundFilename = "background_custom.jpg";
try {
Background.compress(CompressFormat.JPEG, 80, openFileOutput(strBackgroundFilename, MODE_PRIVATE));
} catch (Exception e) {
Log.e(DEBUG_TAG, "Background compression and save failed.", e);
}
Uri imageUriToSaveCameraImageTo = Uri.fromFile(new File(BackgroundSettings.this.getFilesDir(), strBackgroundFilename));
// Load this image
Bitmap bitmapImage = BitmapFactory.decodeFile(imageUriToSaveCameraImageTo.getPath());
Drawable bgrImage = new BitmapDrawable(bitmapImage);
//show it in a view
ImageView backgroundView = (ImageView) findViewById(R.id.BackgroundImageView);
backgroundView.setImageURI(null);
backgroundView.setImageDrawable(bgrImage);
}
File file = new File( url.getAbsolutePath(), imageUrl);
if (file.exists()) {
mDrawable = Drawable.createFromPath(file.getAbsolutePath());
}
I suggest checking that the drawable is being loaded correctly. Some things to try:
Try using a different image on the sd card
Put pic.png in R.drawable and make sure mRoot.setBackgroundResource() does what you expect
After loading the drawable, check d.getBounds() to make sure it is what you expect

Categories

Resources