I am trying to decode the image before drawing it in Canvas. The procedure I followed is same as mentioned in http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
Issue :
The image is scaled only to 70% of the screen. Can you please let me know if I miss any parameters ?
public Bitmap getAssetImage(Context context, String filename) throws IOException {
//Decode image size
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.backgroundhomepage, options);
//The new size we want to scale to
final int REQUIRED_WIDTH= (int) dWidth;
final int REQUIRED_HIGHT= (int) dHeight;
//Find the correct scale value. It should be the power of 2.
int inSampleSize=1;
if (options.outHeight > REQUIRED_HIGHT || options.outWidth > REQUIRED_WIDTH) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) options.outHeight / (float) REQUIRED_HIGHT);
final int widthRatio = Math.round((float) options.outWidth / (float) REQUIRED_WIDTH);
// Choose the smallest ratio as inSampleSize value, this will guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
/*
while(options.outWidth/inSampleSize/2>=REQUIRED_WIDTH && options.outHeight/inSampleSize/2>=REQUIRED_HIGHT)
inSampleSize*=2; */
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=inSampleSize;
o2.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(getApplicationContext().getResources(),R.drawable.backgroundhomepage, o2);
}
public void run() {
// TODO Auto-generated method stub
// Log.i("Notice", "In run of mybringback");
if(backgoundImage == null){
try {Log.i("MyBringBack", "In run of mybringback.. getting the image of background");
backgoundImage = getAssetImage(getApplicationContext(),"backgroundhomepage");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ourHolder = getHolder();
while (isRunning) {
// Log.i("DragDrop", "ourHolder.getSurface().isValid()" + ourHolder.getSurface().isValid() );
if (!ourHolder.getSurface().isValid()){
continue;
}
canvas = ourHolder.lockCanvas();
screenCenterX = dWidth / 2;
screenCenterY = dHeight / 2;
canvas.drawBitmap(backgoundImage, 0, 0, null);
if (imagePublishDone) {
if(!welcomeDone){
message = "Drop your wish to panda";
tts.speak(message, TextToSpeech.QUEUE_FLUSH, null);
welcomeDone=true;
}
moveImageInEllipticalPath();
} else {
initialImagePublish();
}
centreReached = false;
ourHolder.unlockCanvasAndPost(canvas);
}
}
final int REQUIRED_WIDTH= Screen_width;
final int REQUIRED_HIGHT= screen_height;
Calculate screen dimensions first
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int screen_width = size.x;
int screen_height = size.y;
Related
Bitmap bmp = getResizedBitmap(
BitmapFactory.decodeByteArray(data, 0, data.length),
500);
public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float) width / (float) height;
if (bitmapRatio > 0) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}
This is my code Using getResizedBitmap i able to reduced image size but unable to keep its original quality in android please tell me how to keep quality Good so that image Size reduce and Quality should not bad please suggest me !
hi please try below code hope it meets which you want
public static Bitmap scaleImage(String p_path, int p_reqHeight, int p_reqWidth) throws Throwable
{
Bitmap m_bitMap = null;
System.gc();
File m_file = new File(p_path);
if (m_file.exists())
{
BitmapFactory.Options m_bitMapFactoryOptions = new BitmapFactory.Options();
m_bitMapFactoryOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(m_file.getPath(), m_bitMapFactoryOptions);
m_bitMapFactoryOptions.inSampleSize = calculateInSampleSize(m_bitMapFactoryOptions, p_reqHeight, p_reqWidth);
m_bitMapFactoryOptions.inJustDecodeBounds = false;
m_bitMap = BitmapFactory.decodeFile(m_file.getPath(), m_bitMapFactoryOptions);
}
else
{
throw new Throwable(p_path + " not found or not a valid image");
}
return m_bitMap;
}
// Helper method
private static int calculateInSampleSize(BitmapFactory.Options p_options, int p_reqWidth, int p_reqHeight)
{
// Raw height and width of image
final int m_height = p_options.outHeight;
final int m_width = p_options.outWidth;
int m_inSampleSize = 1;
if (m_height > p_reqHeight || m_width > p_reqWidth)
{
final int m_halfHeight = m_height / 2;
final int m_halfWidth = m_width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((m_halfHeight / m_inSampleSize) > p_reqHeight && (m_halfWidth / m_inSampleSize) > p_reqWidth)
{
m_inSampleSize *= 2;
}
}
return m_inSampleSize;
}
I am having a strange behaviour when trying to decode a photo of the size 2448x2448 pixels. In code, I am calculating that a inSampleSize of 6 should be applied (based on the required size of the resulting bitmap) and when I call BitmapFactory.decodeStream with those options I am expecting a bitmap like this:
full_photo_width = 2448
full_photo_height = 2448
inSampleSize = 6
expected_width = (2448 / 6) = 408
expected_height (2448 / 6) = 408
actual_width = 612
actual_height = 612
Here is the code:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
try {
BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
int photo_width = options.outWidth;
int photo_height = options.outHeight;
float rotation = rotationForImage(this, uri);
if (rotation != 0f) {
// Assume the photo is portrait oriented
matrix.preRotate(rotation);
float photo_ratio = (float) ((float)photo_width / (float)photo_height);
frame_height = (int) (frame_width / photo_ratio);
} else {
// Assume the photo is landscape oriented
float photo_ratio = (float) ((float)photo_height / (float)photo_width);
frame_height = (int) (frame_width * photo_ratio);
}
int sampleSize = calculateInSampleSize(options, frame_width, frame_height);
if ((sampleSize % 2) != 0) {
sampleSize++;
}
options.inSampleSize = sampleSize;
options.inJustDecodeBounds = false;
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And the calculateInSampleSize function:
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
// We round the value to the highest, always.
if ((height / inSampleSize) > reqHeight || (width / inSampleSize > reqWidth)) {
inSampleSize++;
}
}
return inSampleSize;
}
The code works for all the photos for all the photos and decodeStream is returning a bitmap with the correct size (depending on the calculated inSampleSize) in all the cases, except with a particular photo. Am I missing something here?
Thanks!
Please refer to official API documentation: inSampleSize.
Note: the decoder uses a final value based on powers of 2, any other value will be rounded down to the nearest power of 2.
I am needing some help with resizing a bitmap before sending it to the wallpaper manager so that when the user sets it as their wallpaper, it fits reasonably, 100% would be preferred.
I am using wallpaper manager and am getting the image from an ImageView.
The issue I am having is the wallpaper is really zoomed in. Before, when I set the wallpaper straight from the drawable directory, it looked fine and you could see a lot more of the image, not 1/4 of it. I have changed my code up since then and have found a lot more of an effective way to get my images and set the wallpaper.
I have looked at This link here and am trying to figure out how to implement the answer that shows you how to resize the image before sending it to the wallpaper manager.
Any help would be appreciated, cheers.
Relative code to question:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.image_detail_fragment,
container, false);
int Measuredwidth = 0;
int Measuredheight = 0;
WindowManager w = getActivity().getWindowManager();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
w.getDefaultDisplay().getSize(Size);
Measuredwidth = Size.x;
Measuredheight = Size.y;
} else {
Display d = w.getDefaultDisplay();
Measuredwidth = d.getWidth();
Measuredheight = d.getHeight();
}
mImageView = (RecyclingImageView) v.findViewById(R.id.imageView);
mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
BitmapDrawable drawable = (BitmapDrawable) mImageView
.getDrawable();
Bitmap bitmap = drawable.getBitmap();
WallpaperManager myWallpaperManager = WallpaperManager
.getInstance(getActivity());
try {
myWallpaperManager.setBitmap(bitmap);
;
Toast.makeText(getActivity(),
"Wallpaper Successfully Set!", Toast.LENGTH_LONG)
.show();
} catch (IOException e) {
Toast.makeText(getActivity(), "Error Setting Wallpaper",
Toast.LENGTH_LONG).show();
}
}
My whole class:
public class ImageDetailFragment extends Fragment {
private static final String IMAGE_DATA_EXTRA = "extra_image_data";
private static final Point Size = null;
private String mImageUrl;
private RecyclingImageView mImageView;
private ImageFetcher mImageFetcher;
public static ImageDetailFragment newInstance(String imageUrl) {
final ImageDetailFragment f = new ImageDetailFragment();
final Bundle args = new Bundle();
args.putString(IMAGE_DATA_EXTRA, imageUrl);
f.setArguments(args);
return f;
}
public ImageDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mImageUrl = getArguments() != null ? getArguments().getString(
IMAGE_DATA_EXTRA) : null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.image_detail_fragment,
container, false);
int Measuredwidth = 0;
int Measuredheight = 0;
WindowManager w = getActivity().getWindowManager();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
w.getDefaultDisplay().getSize(Size);
Measuredwidth = Size.x;
Measuredheight = Size.y;
} else {
Display d = w.getDefaultDisplay();
Measuredwidth = d.getWidth();
Measuredheight = d.getHeight();
}
mImageView = (RecyclingImageView) v.findViewById(R.id.imageView);
mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
BitmapDrawable drawable = (BitmapDrawable) mImageView
.getDrawable();
Bitmap bitmap = drawable.getBitmap();
WallpaperManager myWallpaperManager = WallpaperManager
.getInstance(getActivity());
try {
myWallpaperManager.setBitmap(bitmap);
;
Toast.makeText(getActivity(),
"Wallpaper Successfully Set!", Toast.LENGTH_LONG)
.show();
} catch (IOException e) {
Toast.makeText(getActivity(), "Error Setting Wallpaper",
Toast.LENGTH_LONG).show();
}
}
});
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (Batmanark.class.isInstance(getActivity())) {
mImageFetcher = ((Batmanark) getActivity()).getImageFetcher();
mImageFetcher.loadImage(mImageUrl, mImageView);
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mImageView != null) {
// Cancel any pending image work
ImageWorker.cancelWork(mImageView);
mImageView.setImageDrawable(null);
}
}
}
if you want to fit the wallpaper with the divice screen, then you have to follow the steps bellow:
get the height and width of the divice screen
sample the bitmap image
resize the bitmap
before setting the bitmap as wallpaper, recycle the previous bitmap
code:
step 1:
int Measuredwidth = 0;
int Measuredheight = 0;
Point size = new Point();
// if you are doing it from an activity
WindowManager w = getWindowManager();
// otherwise use this
WindowManager w = context.getWindowManager();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
w.getDefaultDisplay().getSize(size);
Measuredwidth = size.x;
Measuredheight = size.y;
} else {
Display d = w.getDefaultDisplay();
Measuredwidth = d.getWidth();
Measuredheight = d.getHeight();
}
step 2+3:
public Bitmap resizeBitmap(Resources res, int reqWidth, int reqHeight,
InputStream inputStream, int fileLength) {
Bitmap bitmap = null;
InputStream in = null;
InputStream in2 = null;
InputStream in3 = null;
try {
in3 = inputStream;
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream out2 = new ByteArrayOutputStream();
copy(in3,out,fileLength);
out2 = out;
in2 = new ByteArrayInputStream(out.toByteArray());
in = new ByteArrayInputStream(out2.toByteArray());
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, options);
if(options.outHeight == -1 || options.outWidth == 1 || options.outMimeType == null){
return null;
}
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeStream(in2, null, options);
if(bitmap != null){
bitmap = Bitmap.createScaledBitmap(bitmap, reqWidth, reqHeight, false);
}
in.close();
in2.close();
in3.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee a final image
// with both dimensions larger than or equal to the requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
// This offers some additional logic in case the image has a strange
// aspect ratio. For example, a panorama may have a much larger
// width than height. In these cases the total pixels might still
// end up being too large to fit comfortably in memory, so we should
// be more aggressive with sample down the image (=larger inSampleSize).
final float totalPixels = width * height;
// Anything more than 2x the requested pixels we'll sample down further
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
}
return inSampleSize;
}
public int copy(InputStream input, OutputStream output, int fileLength) throws IOException{
byte[] buffer = new byte[8*1024];
int count = 0;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
publishProgress((int) (count * 100 / fileLength));
}
return count;
}
step 4:
to recycle the bitmap use:
bitmap.recycle();
bitmap = null;
call the function like resizeBitmap(context.getResources(), Measuredwidth, Measuredheight,
THE_INPUTSTREAM_FROM_WHERE_YOU_ARE_DOWNLOADING_THE_IMAGE,
FILELENGTH_FROM_THE_INPUTSTREAM);.
if you are calling the function from an activity the call it like: resizeBitmap(getResources(), Measuredwidth, Measuredheight,
THE_INPUTSTREAM_FROM_WHERE_YOU_ARE_DOWNLOADING_THE_IMAGE, FILELENGTH_FROM_THE_INPUTSTREAM);
the function will return resized bitmap which will fit with the divice resulation.
if you have already setted a bitmap as wallpaper, then don't forget to recycle the bitmap before you set a new bitmap as wallpaper.
Please see the function and change the size according to your need. Thanks
public Bitmap createScaledImage(Bitmap bit) {
Bitmap bitmapOrg = bit;
int width = bitmapOrg.getWidth();
int height = bitmapOrg.getHeight();
int newWidth = 0, newHeight = 0;
if (MyDevice.getInstance().getDeviceSize().equals("XLARGE")) {
MyDevice.getInstance().SCALE = 65;
newWidth = 65;
newHeight = 65;
} else if (MyDevice.getInstance().getDeviceSize().equals("LARGE")) {
MyDevice.getInstance().SCALE = 60;
newWidth = 60;
newHeight = 60;
}
else if (MyDevice.getInstance().getDeviceSize().equals("NORMAL")) {
MyDevice.getInstance().SCALE = 50;
newWidth = 50;
newHeight = 50;
if (h > 800) {
MyDevice.getInstance().SCALE = 60;
newWidth = 60;
newHeight = 60;
}
} else if (MyDevice.getInstance().getDeviceSize().equals("SMALL")) {
MyDevice.getInstance().SCALE = 30;
newWidth = 30;
newHeight = 30;
}
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, width,
height, matrix, true);
return resizedBitmap;
}
Where MyDevice is a singleton class here. You can change it as you want. getdevicesize method determines what device it is.
I have tried setting dithering everywhere I can find. I also tried setting everything to ARGB_8888 and STILL there is very bad banding on my background image. My background image is 640x960 and it works fine on my physical phone that is 720x1280 but on an emulator running at 320x480 I get the bad color banding. I put my code below. If you have any suggestions please help!
public void onCreate(Bundle instanceBundle) {
super.onCreate(instanceBundle);
Window window = getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
window.setFormat( PixelFormat.RGBA_8888 );
surfaceView = new SurfaceView(this);
setContentView(surfaceView);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.setFormat( PixelFormat.RGBA_8888 );
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
if(width > height) {
setOffscreenSurface(height, width);
} else {
setOffscreenSurface(width, height);
}
surfaceView.setFocusableInTouchMode(true);
surfaceView.requestFocus();
surfaceView.setOnKeyListener(this);
background = decodeSampledBitmapFromResource( getResources(), R.drawable.background );
}
public Bitmap decodeSampledBitmapFromResource( Resources res, int resId )
{
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options );
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
options.inDither = true;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
return BitmapFactory.decodeResource(res, resId, options);
}
public int calculateInSampleSize( BitmapFactory.Options options )
{
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
int reqWidth = Math.round( width * vertDispRatio );
int reqHeight = Math.round( height * horiDispRatio );
if( height > reqHeight || width > reqWidth )
{
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round( (float) height / (float) reqHeight );
final int widthRatio = Math.round( (float) width / (float) reqWidth );
// Choose the smallest ratio as inSampleSize value, this will guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
#Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
Window window = getWindow();
window.setFormat(PixelFormat.RGBA_8888);
}
public void setOffscreenSurface(int width, int height) {
if(offscreenSurface != null) offscreenSurface.recycle();
offscreenSurface = Bitmap.createBitmap(width, height, Config.ARGB_8888);
canvas = new Canvas(offscreenSurface);
}
Paint paint = new Paint();
public void drawBitmap(Bitmap bitmap, float x, float y)
{
if(canvas != null)
{
int pixelX = (int)( x * getFramebufferWidth() );
int pixelY = (int)( y * getFramebufferHeight() );
paint.setDither(true);
canvas.drawBitmap(bitmap, pixelX, pixelY, paint);
}
}
public void run() {
int frames = 0;
long startTime = System.nanoTime();
long lastTime = System.nanoTime();
while(true) {
if( state == State.Running )
{
if( !surfaceHolder.getSurface().isValid() )
continue;
Canvas canvas = surfaceHolder.lockCanvas();
long currTime = System.nanoTime();
float deltaTime = (currTime - lastTime) / 1000000000.0f;
if( deltaTime > 0.1f )
deltaTime = 0.1f;
clearFramebuffer( Color.BLACK );
drawBitmap( background, 0, 0 );
src.left = 0;
src.top = 0;
src.right = offscreenSurface.getWidth() - 1;
src.bottom = offscreenSurface.getHeight() - 1;
dst.left = 0;
dst.top = 0;
dst.right = surfaceView.getWidth();
dst.bottom = surfaceView.getHeight();
canvas.drawBitmap(offscreenSurface, src, dst, null);
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
I dont see anywhere in your code where your trying to set anti aliasing. You can also do that with the paint you use in your canvas. that should help and if not maybe the device you are using just sucks? :P
Edit:
I swore that you could set anti-aliasing through bitmapfactory but I guess not. You can definitely do it from paint though. You can set it by using the paint.setAntiAlias(aa) method.
I am developing an application that shows the different photos from the server and the user can set selected photos as wallpaper of its device I used the given code to set wallpaper it works but the image was not set correctly it does not fit to screen. I used this code.
String dirPath = getFilesDir().toString();
String folder = mPhotos.get(nextPosition - 1).getCategory();
String filePath = dirPath + "/PhotoViewer/" + folder + "/"
+ mPhotos.get(nextPosition - 1).getFileName();
File imageFile = new File(filePath);
Bitmap bitmap = BitmapFactory.decodeFile(imageFile
.getAbsolutePath());
WallpaperManager myWallpaperManager = WallpaperManager
.getInstance(getApplicationContext());
try
{
myWallpaperManager.setBitmap(bitmap);
Toast.makeText(PhotoActivity.this, "Wallpaper set",
Toast.LENGTH_SHORT).show();
} catch(IOException e){
Toast.makeText(PhotoActivity.this, "Error setting wallpaper",
Toast.LENGTH_SHORT).show();
}
To set wallpaper in android use the below code: By using WallpaperManager Class
Button buttonSetWallpaper = (Button)findViewById(R.id.set);
ImageView imagePreview = (ImageView)findViewById(R.id.preview);
imagePreview.setImageResource(R.drawable.five);
buttonSetWallpaper.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setResource(R.drawable.five);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Need to set permission in Manifest:
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
You can try resizing your bitmap 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);
}
Your calculateInSampleSize class can be like this
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
Refer this link for further clarifications