Java tutorial
//package com.java2s; /* * Copyright (C) 2014 Kartik Sharma Licensed under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law * or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; public class Main { /** * This is only used when the launcher shortcut is created. * * @param bitmap The artist, album, genre, or playlist image that's going to * be cropped. * @param size The new size. * @return A {@link Bitmap} that has been resized and cropped for a launcher * shortcut. */ public static final Bitmap resizeAndCropCenter(final Bitmap bitmap, final int size) { Bitmap blurbitmap = null; final int w = bitmap.getWidth(); final int h = bitmap.getHeight(); if (w == size && h == size) { return bitmap; } ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos); byte[] bitmapdata = bos.toByteArray(); ByteArrayInputStream bs = new ByteArrayInputStream(bitmapdata); try { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 8; options.inJustDecodeBounds = true; blurbitmap = BitmapFactory.decodeStream(bs, null, options); options.inJustDecodeBounds = false; } catch (Exception e) { e.printStackTrace(); } finally { if (bs != null) { try { bs.close(); } catch (IOException e) { e.printStackTrace(); } } } final float mScale = (float) size / Math.min(w, h); final Bitmap mTarget = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); final int mWidth = Math.round(mScale * blurbitmap.getWidth()); final int mHeight = Math.round(mScale * blurbitmap.getHeight()); final Canvas mCanvas = new Canvas(mTarget); mCanvas.translate((size - mWidth) / 2f, (size - mHeight) / 2f); mCanvas.scale(mScale, mScale); final Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG); mCanvas.drawBitmap(bitmap, 0, 0, paint); return mTarget; } }