android图片处理

Java代码 复制代码 收藏代码 spinner.gif
  1. //压缩图片大小

  2. publicstatic Bitmap compressImage(Bitmap image) {  

  3.        ByteArrayOutputStream baos = new ByteArrayOutputStream();  

  4.        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中

  5. int options = 100;  

  6. while ( baos.toByteArray().length / 1024>100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩      

  7.            baos.reset();//重置baos即清空baos

  8.            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中

  9.            options -= 10;//每次都减少10

  10.        }  

  11.        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中

  12.        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片

  13. return bitmap;  

  14.    }  

//压缩图片大小
	public static Bitmap compressImage(Bitmap image) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
		int options = 100;
		while ( baos.toByteArray().length / 1024>100) {	//循环判断如果压缩后图片是否大于100kb,大于继续压缩		
			baos.reset();//重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中
			options -= 10;//每次都减少10
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
		return bitmap;
	}

Java代码 复制代码 收藏代码 spinner.gif
  1. /**

  2.     * 将彩色图转换为灰度图

  3.     * @param img 位图

  4.     * @return  返回转换好的位图

  5.     */

  6. public Bitmap convertGreyImg(Bitmap img) {    

  7. int width = img.getWidth();         //获取位图的宽  

  8. int height = img.getHeight();       //获取位图的高  

  9. int []pixels = newint[width * height]; //通过位图的大小创建像素点数组  

  10.        img.getPixels(pixels, 0, width, 0, 0, width, height);    

  11. int alpha = 0xFF << 24;    

  12. for(int i = 0; i < height; i++)  {    

  13. for(int j = 0; j < width; j++) {    

  14. int grey = pixels[width * i + j];    

  15. int red = ((grey  & 0x00FF0000 ) >> 16);    

  16. int green = ((grey & 0x0000FF00) >> 8);    

  17. int blue = (grey & 0x000000FF);    

  18.                grey = (int)((float) red * 0.3 + (float)green * 0.59 + (float)blue * 0.11);    

  19.                grey = alpha | (grey << 16) | (grey << 8) | grey;    

  20.                pixels[width * i + j] = grey;    

  21.            }    

  22.        }    

  23.        Bitmap result = Bitmap.createBitmap(width, height, Config.RGB_565);    

  24.        result.setPixels(pixels, 0, width, 0, 0, width, height);    

  25. return result;    

  26.    }    

/** 
     * 将彩色图转换为灰度图 
     * @param img 位图 
     * @return  返回转换好的位图 
     */  
    public Bitmap convertGreyImg(Bitmap img) {  
        int width = img.getWidth();         //获取位图的宽  
        int height = img.getHeight();       //获取位图的高  
          
        int []pixels = new int[width * height]; //通过位图的大小创建像素点数组  
          
        img.getPixels(pixels, 0, width, 0, 0, width, height);  
        int alpha = 0xFF << 24;   
        for(int i = 0; i < height; i++)  {  
            for(int j = 0; j < width; j++) {  
                int grey = pixels[width * i + j];  
                  
                int red = ((grey  & 0x00FF0000 ) >> 16);  
                int green = ((grey & 0x0000FF00) >> 8);  
                int blue = (grey & 0x000000FF);  
                  
                grey = (int)((float) red * 0.3 + (float)green * 0.59 + (float)blue * 0.11);  
                grey = alpha | (grey << 16) | (grey << 8) | grey;  
                pixels[width * i + j] = grey;  
            }  
        }  
        Bitmap result = Bitmap.createBitmap(width, height, Config.RGB_565);  
        result.setPixels(pixels, 0, width, 0, 0, width, height);  
        return result;  
    }  


6d20ecbb-f4c3-39ec-9396-1b6ae2283a3c.png

将一个图片切割成多个图片
有种场景,我们想将一个图片切割成多个图片。比如我们在开发一个拼图的游戏,就首先要对图片进行切割。
以下是封装好的两个类,可以实现图片的切割。仅供参考和学习。
一个是ImagePiece类,此类保存了一个Bitmap对象和一个标识图片的顺序索引的int变量。
Java代码 复制代码 收藏代码 spinner.gif
  1. import android.graphics.Bitmap;  

  2. publicclass ImagePiece {    

  3. publicint index = 0;          

  4. public Bitmap bitmap = null;    

  5. }  

import android.graphics.Bitmap; 
public class ImagePiece {   
    public int index = 0;        
    public Bitmap bitmap = null;  
}

一个是ImageSplitter类,有一个静态方法split,传入的参数是要切割的Bitmap对象,和横向和竖向的切割片数。比如传入的是3、3,则横竖向都切割成3片,最终会将整个图片切割成3X3=9片。
Java代码 复制代码 收藏代码 spinner.gif
  1. import java.util.ArrayList;    

  2. import java.util.List;    

  3. import android.graphics.Bitmap;    

  4. publicclass ImageSplitter {    

  5. publicstatic List<ImagePiece> split(Bitmap bitmap, int xPiece, int yPiece) {    

  6.        List<ImagePiece> pieces = new ArrayList<ImagePiece>(xPiece * yPiece);    

  7. int width = bitmap.getWidth();    

  8. int height = bitmap.getHeight();    

  9. int pieceWidth = width / 3;    

  10. int pieceHeight = height / 3;    

  11. for (int i = 0; i < yPiece; i++) {    

  12. for (int j = 0; j < xPiece; j++) {    

  13.                ImagePiece piece = new ImagePiece();    

  14.                piece.index = j + i * xPiece;    

  15. int xValue = j * pieceWidth;    

  16. int yValue = i * pieceHeight;    

  17.                piece.bitmap = Bitmap.createBitmap(bitmap, xValue, yValue,    

  18.                        pieceWidth, pieceHeight);    

  19.                pieces.add(piece);    

  20.            }    

  21.        }    

  22. return pieces;    

  23.    }    

  24. }  

import java.util.ArrayList;  
import java.util.List;  
  
import android.graphics.Bitmap;  
  
public class ImageSplitter {  
  
    public static List<ImagePiece> split(Bitmap bitmap, int xPiece, int yPiece) {  
  
        List<ImagePiece> pieces = new ArrayList<ImagePiece>(xPiece * yPiece);  
        int width = bitmap.getWidth();  
        int height = bitmap.getHeight();  
        int pieceWidth = width / 3;  
        int pieceHeight = height / 3;  
        for (int i = 0; i < yPiece; i++) {  
            for (int j = 0; j < xPiece; j++) {  
                ImagePiece piece = new ImagePiece();  
                piece.index = j + i * xPiece;  
                int xValue = j * pieceWidth;  
                int yValue = i * pieceHeight;  
                piece.bitmap = Bitmap.createBitmap(bitmap, xValue, yValue,  
                        pieceWidth, pieceHeight);  
                pieces.add(piece);  
            }  
        }  
  
        return pieces;  
    }  
  
}


1、图标加灰色过滤;
2、android的图片资源默认是静态的,单实例;如果两个IM好友的头像一样,最简单的都是用的软件自带头像,有一个在线,一个离线,直接改变头像的灰度,则两个用户的头像都会变灰或者在线,答案是:Drawable.mutate()。
Java代码 复制代码 收藏代码 spinner.gif
  1. Drawable mDrawable = context.getResources().getDrawable(R.drawable.face_icon);    

  2. //Make this drawable mutable.  

  3. //A mutable drawable is guaranteed to not share its state with any other drawable.  

  4. mDrawable.mutate();    

  5. ColorMatrix cm = new ColorMatrix();    

  6. cm.setSaturation(0);    

  7. ColorMatrixColorFilter cf = new ColorMatrixColorFilter(cm);    

  8. mDrawable.setColorFilter(cf);  

Drawable mDrawable = context.getResources().getDrawable(R.drawable.face_icon);  
//Make this drawable mutable.  
//A mutable drawable is guaranteed to not share its state with any other drawable.  
mDrawable.mutate();  
ColorMatrix cm = new ColorMatrix();  
cm.setSaturation(0);  
ColorMatrixColorFilter cf = new ColorMatrixColorFilter(cm);  
mDrawable.setColorFilter(cf);


生成缩略图,抠自android launcher源码:
Java代码 复制代码 收藏代码 spinner.gif
  1. /*

  2. * Copyright (C) 2008 The Android Open Source Project

  3. *

  4. * Licensed under the Apache License, Version 2.0 (the "License");

  5. * you may not use this file except in compliance with the License.

  6. * You may obtain a copy of the License at

  7. *

  8. *      http://www.apache.org/licenses/LICENSE-2.0

  9. *

  10. * Unless required by applicable law or agreed to in writing, software

  11. * distributed under the License is distributed on an "AS IS" BASIS,

  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

  13. * See the License for the specific language governing permissions and

  14. * limitations under the License.

  15. */

  16. package com.android.launcher;  

  17. import android.graphics.drawable.BitmapDrawable;  

  18. import android.graphics.drawable.Drawable;  

  19. import android.graphics.drawable.PaintDrawable;  

  20. import android.graphics.Bitmap;  

  21. import android.graphics.PixelFormat;  

  22. import android.graphics.Canvas;  

  23. import android.graphics.PaintFlagsDrawFilter;  

  24. import android.graphics.Paint;  

  25. import android.graphics.Rect;  

  26. import android.content.res.Resources;  

  27. import android.content.Context;  

  28. /**

  29. * Various utilities shared amongst the Launcher's classes.

  30. */

  31. finalclass Utilities {  

  32. privatestaticint sIconWidth = -1;  

  33. privatestaticint sIconHeight = -1;  

  34. privatestaticfinal Paint sPaint = new Paint();  

  35. privatestaticfinal Rect sBounds = new Rect();  

  36. privatestaticfinal Rect sOldBounds = new Rect();  

  37. privatestatic Canvas sCanvas = new Canvas();  

  38. static {  

  39.        sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,  

  40.                Paint.FILTER_BITMAP_FLAG));  

  41.    }  

  42. /**

  43.     * Returns a Drawable representing the thumbnail of the specified Drawable.

  44.     * The size of the thumbnail is defined by the dimension

  45.     * android.R.dimen.launcher_application_icon_size.

  46.     *

  47.     * This method is not thread-safe and should be invoked on the UI thread only.

  48.     *

  49.     * @param icon The icon to get a thumbnail of.

  50.     * @param context The application's context.

  51.     *

  52.     * @return A thumbnail for the specified icon or the icon itself if the

  53.     *         thumbnail could not be created.

  54.     */

  55. static Drawable createIconThumbnail(Drawable icon, Context context) {  

  56. if (sIconWidth == -1) {  

  57. final Resources resources = context.getResources();  

  58.            sIconWidth = sIconHeight = (int) resources.getDimension(android.R.dimen.app_icon_size);  

  59.        }  

  60. int width = sIconWidth;  

  61. int height = sIconHeight;  

  62. float scale = 1.0f;  

  63. if (icon instanceof PaintDrawable) {  

  64.            PaintDrawable painter = (PaintDrawable) icon;  

  65.            painter.setIntrinsicWidth(width);  

  66.            painter.setIntrinsicHeight(height);  

  67.        } elseif (icon instanceof BitmapDrawable) {  

  68. // Ensure the bitmap has a density.

  69.            BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;  

  70.            Bitmap bitmap = bitmapDrawable.getBitmap();  

  71. if (bitmap.getDensity() == Bitmap.DENSITY_NONE) {  

  72.                bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());  

  73.            }  

  74.        }  

  75. int iconWidth = icon.getIntrinsicWidth();  

  76. int iconHeight = icon.getIntrinsicHeight();  

  77. if (width > 0 && height > 0) {  

  78. if (width < iconWidth || height < iconHeight || scale != 1.0f) {  

  79. finalfloat ratio = (float) iconWidth / iconHeight;  

  80. if (iconWidth > iconHeight) {  

  81.                    height = (int) (width / ratio);  

  82.                } elseif (iconHeight > iconWidth) {  

  83.                    width = (int) (height * ratio);  

  84.                }  

  85. final Bitmap.Config c = icon.getOpacity() != PixelFormat.OPAQUE ?  

  86.                            Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;  

  87. final Bitmap thumb = Bitmap.createBitmap(sIconWidth, sIconHeight, c);  

  88. final Canvas canvas = sCanvas;  

  89.                canvas.setBitmap(thumb);  

  90. // Copy the old bounds to restore them later

  91. // If we were to do oldBounds = icon.getBounds(),

  92. // the call to setBounds() that follows would

  93. // change the same instance and we would lose the

  94. // old bounds

  95.                sOldBounds.set(icon.getBounds());  

  96. finalint x = (sIconWidth - width) / 2;  

  97. finalint y = (sIconHeight - height) / 2;  

  98.                icon.setBounds(x, y, x + width, y + height);  

  99.                icon.draw(canvas);  

  100.                icon.setBounds(sOldBounds);  

  101.                icon = new FastBitmapDrawable(thumb);  

  102.            } elseif (iconWidth < width && iconHeight < height) {  

  103. final Bitmap.Config c = Bitmap.Config.ARGB_8888;  

  104. final Bitmap thumb = Bitmap.createBitmap(sIconWidth, sIconHeight, c);  

  105. final Canvas canvas = sCanvas;  

  106.                canvas.setBitmap(thumb);  

  107.                sOldBounds.set(icon.getBounds());  

  108. finalint x = (width - iconWidth) / 2;  

  109. finalint y = (height - iconHeight) / 2;  

  110.                icon.setBounds(x, y, x + iconWidth, y + iconHeight);  

  111.                icon.draw(canvas);  

  112.                icon.setBounds(sOldBounds);  

  113.                icon = new FastBitmapDrawable(thumb);  

  114.            }  

  115.        }  

  116. return icon;  

  117.    }  

  118. /**

  119.     * Returns a Bitmap representing the thumbnail of the specified Bitmap.

  120.     * The size of the thumbnail is defined by the dimension

  121.     * android.R.dimen.launcher_application_icon_size.

  122.     *

  123.     * This method is not thread-safe and should be invoked on the UI thread only.

  124.     *

  125.     * @param bitmap The bitmap to get a thumbnail of.

  126.     * @param context The application's context.

  127.     *

  128.     * @return A thumbnail for the specified bitmap or the bitmap itself if the

  129.     *         thumbnail could not be created.

  130.     */

  131. static Bitmap createBitmapThumbnail(Bitmap bitmap, Context context) {  

  132. if (sIconWidth == -1) {  

  133. final Resources resources = context.getResources();  

  134.            sIconWidth = sIconHeight = (int) resources.getDimension(  

  135.                    android.R.dimen.app_icon_size);  

  136.        }  

  137. int width = sIconWidth;  

  138. int height = sIconHeight;  

  139. finalint bitmapWidth = bitmap.getWidth();  

  140. finalint bitmapHeight = bitmap.getHeight();  

  141. if (width > 0 && height > 0) {  

  142. if (width < bitmapWidth || height < bitmapHeight) {  

  143. finalfloat ratio = (float) bitmapWidth / bitmapHeight;  

  144. if (bitmapWidth > bitmapHeight) {  

  145.                    height = (int) (width / ratio);  

  146.                } elseif (bitmapHeight > bitmapWidth) {  

  147.                    width = (int) (height * ratio);  

  148.                }  

  149. final Bitmap.Config c = (width == sIconWidth && height == sIconHeight) ?  

  150.                        bitmap.getConfig() : Bitmap.Config.ARGB_8888;  

  151. final Bitmap thumb = Bitmap.createBitmap(sIconWidth, sIconHeight, c);  

  152. final Canvas canvas = sCanvas;  

  153. final Paint paint = sPaint;  

  154.                canvas.setBitmap(thumb);  

  155.                paint.setDither(false);  

  156.                paint.setFilterBitmap(true);  

  157.                sBounds.set((sIconWidth - width) / 2, (sIconHeight - height) / 2, width, height);  

  158.                sOldBounds.set(0, 0, bitmapWidth, bitmapHeight);  

  159.                canvas.drawBitmap(bitmap, sOldBounds, sBounds, paint);  

  160. return thumb;  

  161.            } elseif (bitmapWidth < width || bitmapHeight < height) {  

  162. final Bitmap.Config c = Bitmap.Config.ARGB_8888;  

  163. final Bitmap thumb = Bitmap.createBitmap(sIconWidth, sIconHeight, c);  

  164. final Canvas canvas = sCanvas;  

  165. final Paint paint = sPaint;  

  166.                canvas.setBitmap(thumb);  

  167.                paint.setDither(false);  

  168.                paint.setFilterBitmap(true);  

  169.                canvas.drawBitmap(bitmap, (sIconWidth - bitmapWidth) / 2,  

  170.                        (sIconHeight - bitmapHeight) / 2, paint);  

  171. return thumb;  

  172.            }  

  173.        }  

  174. return bitmap;  

  175.    }  

  176. }  

/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * 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.
 */

package com.android.launcher;

import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.PaintDrawable;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.graphics.Canvas;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.Paint;
import android.graphics.Rect;
import android.content.res.Resources;
import android.content.Context;

/**
 * Various utilities shared amongst the Launcher's classes.
 */
final class Utilities {
    private static int sIconWidth = -1;
    private static int sIconHeight = -1;

    private static final Paint sPaint = new Paint();
    private static final Rect sBounds = new Rect();
    private static final Rect sOldBounds = new Rect();
    private static Canvas sCanvas = new Canvas();

    static {
        sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG,
                Paint.FILTER_BITMAP_FLAG));
    }

    /**
     * Returns a Drawable representing the thumbnail of the specified Drawable.
     * The size of the thumbnail is defined by the dimension
     * android.R.dimen.launcher_application_icon_size.
     *
     * This method is not thread-safe and should be invoked on the UI thread only.
     *
     * @param icon The icon to get a thumbnail of.
     * @param context The application's context.
     *
     * @return A thumbnail for the specified icon or the icon itself if the
     *         thumbnail could not be created. 
     */
    static Drawable createIconThumbnail(Drawable icon, Context context) {
        if (sIconWidth == -1) {
            final Resources resources = context.getResources();
            sIconWidth = sIconHeight = (int) resources.getDimension(android.R.dimen.app_icon_size);
        }

        int width = sIconWidth;
        int height = sIconHeight;

        float scale = 1.0f;
        if (icon instanceof PaintDrawable) {
            PaintDrawable painter = (PaintDrawable) icon;
            painter.setIntrinsicWidth(width);
            painter.setIntrinsicHeight(height);
        } else if (icon instanceof BitmapDrawable) {
            // Ensure the bitmap has a density.
            BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
            Bitmap bitmap = bitmapDrawable.getBitmap();
            if (bitmap.getDensity() == Bitmap.DENSITY_NONE) {
                bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
            }
        }
        int iconWidth = icon.getIntrinsicWidth();
        int iconHeight = icon.getIntrinsicHeight();

        if (width > 0 && height > 0) {
            if (width < iconWidth || height < iconHeight || scale != 1.0f) {
                final float ratio = (float) iconWidth / iconHeight;

                if (iconWidth > iconHeight) {
                    height = (int) (width / ratio);
                } else if (iconHeight > iconWidth) {
                    width = (int) (height * ratio);
                }

                final Bitmap.Config c = icon.getOpacity() != PixelFormat.OPAQUE ?
                            Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
                final Bitmap thumb = Bitmap.createBitmap(sIconWidth, sIconHeight, c);
                final Canvas canvas = sCanvas;
                canvas.setBitmap(thumb);
                // Copy the old bounds to restore them later
                // If we were to do oldBounds = icon.getBounds(),
                // the call to setBounds() that follows would
                // change the same instance and we would lose the
                // old bounds
                sOldBounds.set(icon.getBounds());
                final int x = (sIconWidth - width) / 2;
                final int y = (sIconHeight - height) / 2;
                icon.setBounds(x, y, x + width, y + height);
                icon.draw(canvas);
                icon.setBounds(sOldBounds);
                icon = new FastBitmapDrawable(thumb);
            } else if (iconWidth < width && iconHeight < height) {
                final Bitmap.Config c = Bitmap.Config.ARGB_8888;
                final Bitmap thumb = Bitmap.createBitmap(sIconWidth, sIconHeight, c);
                final Canvas canvas = sCanvas;
                canvas.setBitmap(thumb);
                sOldBounds.set(icon.getBounds());
                final int x = (width - iconWidth) / 2;
                final int y = (height - iconHeight) / 2;
                icon.setBounds(x, y, x + iconWidth, y + iconHeight);
                icon.draw(canvas);
                icon.setBounds(sOldBounds);
                icon = new FastBitmapDrawable(thumb);
            }
        }

        return icon;
    }

    /**
     * Returns a Bitmap representing the thumbnail of the specified Bitmap.
     * The size of the thumbnail is defined by the dimension
     * android.R.dimen.launcher_application_icon_size.
     *
     * This method is not thread-safe and should be invoked on the UI thread only.
     *
     * @param bitmap The bitmap to get a thumbnail of.
     * @param context The application's context.
     *
     * @return A thumbnail for the specified bitmap or the bitmap itself if the
     *         thumbnail could not be created.
     */
    static Bitmap createBitmapThumbnail(Bitmap bitmap, Context context) {
        if (sIconWidth == -1) {
            final Resources resources = context.getResources();
            sIconWidth = sIconHeight = (int) resources.getDimension(
                    android.R.dimen.app_icon_size);
        }

        int width = sIconWidth;
        int height = sIconHeight;

        final int bitmapWidth = bitmap.getWidth();
        final int bitmapHeight = bitmap.getHeight();

        if (width > 0 && height > 0) {
            if (width < bitmapWidth || height < bitmapHeight) {
                final float ratio = (float) bitmapWidth / bitmapHeight;
    
                if (bitmapWidth > bitmapHeight) {
                    height = (int) (width / ratio);
                } else if (bitmapHeight > bitmapWidth) {
                    width = (int) (height * ratio);
                }
    
                final Bitmap.Config c = (width == sIconWidth && height == sIconHeight) ?
                        bitmap.getConfig() : Bitmap.Config.ARGB_8888;
                final Bitmap thumb = Bitmap.createBitmap(sIconWidth, sIconHeight, c);
                final Canvas canvas = sCanvas;
                final Paint paint = sPaint;
                canvas.setBitmap(thumb);
                paint.setDither(false);
                paint.setFilterBitmap(true);
                sBounds.set((sIconWidth - width) / 2, (sIconHeight - height) / 2, width, height);
                sOldBounds.set(0, 0, bitmapWidth, bitmapHeight);
                canvas.drawBitmap(bitmap, sOldBounds, sBounds, paint);
                return thumb;
            } else if (bitmapWidth < width || bitmapHeight < height) {
                final Bitmap.Config c = Bitmap.Config.ARGB_8888;
                final Bitmap thumb = Bitmap.createBitmap(sIconWidth, sIconHeight, c);
                final Canvas canvas = sCanvas;
                final Paint paint = sPaint;
                canvas.setBitmap(thumb);
                paint.setDither(false);
                paint.setFilterBitmap(true);
                canvas.drawBitmap(bitmap, (sIconWidth - bitmapWidth) / 2,
                        (sIconHeight - bitmapHeight) / 2, paint);
                return thumb;
            }
        }

        return bitmap;
    }
}


Java代码 复制代码 收藏代码 spinner.gif
  1. //Android Matrix类实现镜像方法

  2. publicvoid drawRegion(Image image_src,  

  3. int x_src, int y_src,  

  4. int width, int height,  

  5. int transform,  

  6. int x_dest, int y_dest,  

  7. int anchor){  

  8. if((anchor&VCENTER) != 0){  

  9. y_dest -= height/2;  

  10. }elseif((anchor&BOTTOM) != 0){  

  11. y_dest -= height;  

  12. }  

  13. if((anchor&RIGHT) != 0){  

  14. x_dest -= width;  

  15. }elseif((anchor&HCENTER) != 0){  

  16. x_dest -= width/2;  

  17. }  

  18. Bitmap newMap = Bitmap.createBitmap(image_src.getBitmap(), x_src, y_src, width, height);  

  19. Matrix mMatrix = new Matrix();  

  20. Matrix temp = new Matrix();  

  21. Matrix temp2 = new Matrix();  

  22. float[] mirrorY = {  

  23. -1, 0, 0,  

  24. 0, 1, 0,  

  25. 0, 0, 1

  26. };  

  27. temp.setValues(mirrorY);  

  28. switch(transform){  

  29. case Sprite.TRANS_NONE:  

  30. break;  

  31. case Sprite.TRANS_ROT90:  

  32. mMatrix.setRotate(90,width/2, height/2);  

  33. break;  

  34. case Sprite.TRANS_ROT180:  

  35. mMatrix.setRotate(180,width/2, height/2);  

  36. break;  

  37. case Sprite.TRANS_ROT270:  

  38. mMatrix.setRotate(270,width/2, height/2);  

  39. break;  

  40. case Sprite.TRANS_MIRROR:  

  41. mMatrix.postConcat(temp);  

  42. break;  

  43. case Sprite.TRANS_MIRROR_ROT90:  

  44. mMatrix.postConcat(temp);  

  45. mMatrix.setRotate(90,width/2, height/2);  

  46. break;  

  47. case Sprite.TRANS_MIRROR_ROT180:  

  48. mMatrix.postConcat(temp);  

  49. mMatrix.setRotate(180,width/2, height/2);  

  50. break;  

  51. case Sprite.TRANS_MIRROR_ROT270:  

  52. mMatrix.postConcat(temp);  

  53. mMatrix.setRotate(270,width/2, height/2);  

  54. break;  

  55. }  

  56. mMatrix.setTranslate(x_dest, y_dest);  

  57. canvas.drawBitmap(newMap, mMatrix, mPaint);  

  58. }  

//Android Matrix类实现镜像方法
public void drawRegion(Image image_src,

int x_src, int y_src,

int width, int height,

int transform,

int x_dest, int y_dest,

int anchor){

if((anchor&VCENTER) != 0){

y_dest -= height/2;

}else if((anchor&BOTTOM) != 0){

y_dest -= height;

}

if((anchor&RIGHT) != 0){

x_dest -= width;

}else if((anchor&HCENTER) != 0){

x_dest -= width/2;

}

Bitmap newMap = Bitmap.createBitmap(image_src.getBitmap(), x_src, y_src, width, height);

Matrix mMatrix = new Matrix();

Matrix temp = new Matrix();

Matrix temp2 = new Matrix();

float[] mirrorY = {

-1, 0, 0,
0, 1, 0,
0, 0, 1

};

temp.setValues(mirrorY);

switch(transform){

case Sprite.TRANS_NONE:

break;

case Sprite.TRANS_ROT90:

mMatrix.setRotate(90,width/2, height/2);

break;

case Sprite.TRANS_ROT180:

mMatrix.setRotate(180,width/2, height/2);

break;

case Sprite.TRANS_ROT270:

mMatrix.setRotate(270,width/2, height/2);

break;

case Sprite.TRANS_MIRROR:

mMatrix.postConcat(temp);

break;

case Sprite.TRANS_MIRROR_ROT90:

mMatrix.postConcat(temp);

mMatrix.setRotate(90,width/2, height/2);

break;

case Sprite.TRANS_MIRROR_ROT180:

mMatrix.postConcat(temp);

mMatrix.setRotate(180,width/2, height/2);

break;

case Sprite.TRANS_MIRROR_ROT270:

mMatrix.postConcat(temp);

mMatrix.setRotate(270,width/2, height/2);

break;

}

mMatrix.setTranslate(x_dest, y_dest);

canvas.drawBitmap(newMap, mMatrix, mPaint);

}


Java代码 复制代码 收藏代码 spinner.gif
  1. //图片Url保存为位图并进行缩放操作

  2. //通过传入图片url获取位图方法

  3. public Bitmap returnBitMap(String url) {  

  4.        URL myFileUrl = null;  

  5.        Bitmap bitmap = null;  

  6. try {  

  7.            myFileUrl = new URL(url);  

  8.        } catch (MalformedURLException e) {  

  9.            e.printStackTrace();  

  10.        }  

  11. try {  

  12.            HttpURLConnection conn = (HttpURLConnection) myFileUrl  

  13.                    .openConnection();  

  14.            conn.setDoInput(true);  

  15.            conn.connect();  

  16.            InputStream is = conn.getInputStream();  

  17.            bitmap = BitmapFactory.decodeStream(is);  

  18.            is.close();  

  19.        } catch (IOException e) {  

  20.            e.printStackTrace();  

  21.        }  

  22.        Log.v(tag, bitmap.toString());  

  23. return bitmap;  

  24.    }  

  25. //通过传入位图,新的宽.高比进行位图的缩放操作

  26. publicstatic Drawable resizeImage(Bitmap bitmap, int w, int h) {  

  27. // load the origial Bitmap

  28.        Bitmap BitmapOrg = bitmap;  

  29. int width = BitmapOrg.getWidth();  

  30. int height = BitmapOrg.getHeight();  

  31. int newWidth = w;  

  32. int newHeight = h;  

  33.        Log.v(tag, String.valueOf(width));  

  34.        Log.v(tag, String.valueOf(height));  

  35.        Log.v(tag, String.valueOf(newWidth));  

  36.        Log.v(tag, String.valueOf(newHeight));  

  37. // calculate the scale

  38. float scaleWidth = ((float) newWidth) / width;  

  39. float scaleHeight = ((float) newHeight) / height;  

  40. // create a matrix for the manipulation

  41.        Matrix matrix = new Matrix();  

  42. // resize the Bitmap

  43.        matrix.postScale(scaleWidth, scaleHeight);  

  44. // if you want to rotate the Bitmap

  45. // matrix.postRotate(45);

  46. // recreate the new Bitmap

  47.        Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,  

  48.                height, matrix, true);  

  49. // make a Drawable from Bitmap to allow to set the Bitmap

  50. // to the ImageView, ImageButton or what ever

  51. returnnew BitmapDrawable(resizedBitmap);  

  52.    }  

//图片Url保存为位图并进行缩放操作
//通过传入图片url获取位图方法
public Bitmap returnBitMap(String url) {
		URL myFileUrl = null;
		Bitmap bitmap = null;
		try {
			myFileUrl = new URL(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		try {
			HttpURLConnection conn = (HttpURLConnection) myFileUrl
					.openConnection();
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is);
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Log.v(tag, bitmap.toString());

		return bitmap;
	}
//通过传入位图,新的宽.高比进行位图的缩放操作
public static Drawable resizeImage(Bitmap bitmap, int w, int h) {

		// load the origial Bitmap
		Bitmap BitmapOrg = bitmap;

		int width = BitmapOrg.getWidth();
		int height = BitmapOrg.getHeight();
		int newWidth = w;
		int newHeight = h;

		Log.v(tag, String.valueOf(width));
		Log.v(tag, String.valueOf(height));

		Log.v(tag, String.valueOf(newWidth));
		Log.v(tag, String.valueOf(newHeight));

		// calculate the scale
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;

		// create a matrix for the manipulation
		Matrix matrix = new Matrix();
		// resize the Bitmap
		matrix.postScale(scaleWidth, scaleHeight);
		// if you want to rotate the Bitmap
		// matrix.postRotate(45);

		// recreate the new Bitmap
		Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
				height, matrix, true);

		// make a Drawable from Bitmap to allow to set the Bitmap
		// to the ImageView, ImageButton or what ever
		return new BitmapDrawable(resizedBitmap);

	}


Java代码 复制代码 收藏代码 spinner.gif
  1. 1.图片加载方法,方便用户加载图片  

  2. /***

  3. * 加载本地图片

  4. * @param context:主运行函数实例

  5. * @param bitAdress:图片地址,一般指向R下的drawable目录

  6. * @return

  7. */

  8. publicfinal Bitmap CreatImage(Context context, int bitAdress) {  

  9. Bitmap bitmaptemp = null;  

  10. bitmaptemp = BitmapFactory.decodeResource(context.getResources(),  

  11. bitAdress);  

  12. return bitmaptemp;  

  13. }  

  14. 2.图片平均分割方法,将大图平均分割为N行N列,方便用户使用  

  15. /***

  16. * 图片分割

  17. *

  18. * @param g

  19. * :画布

  20. * @param paint

  21. * :画笔

  22. * @param imgBit

  23. * :图片

  24. * @param x

  25. * :X轴起点坐标

  26. * @param y

  27. * :Y轴起点坐标

  28. * @param w

  29. * :单一图片的宽度

  30. * @param h

  31. * :单一图片的高度

  32. * @param line

  33. * :第几列

  34. * @param row

  35. * :第几行

  36. */

  37. publicfinalvoid cuteImage(Canvas g, Paint paint, Bitmap imgBit, int x,  

  38. int y, int w, int h, int line, int row) {  

  39. g.clipRect(x, y, x + w, h + y);  

  40. g.drawBitmap(imgBit, x �C line * w, y �C row * h, paint);  

  41. g.restore();  

  42. }  

  43. 3.图片缩放,对当前图片进行缩放处理  

  44. /***

  45. * 图片的缩放方法

  46. *

  47. * @param bgimage

  48. * :源图片资源

  49. * @param newWidth

  50. * :缩放后宽度

  51. * @param newHeight

  52. * :缩放后高度

  53. * @return

  54. */

  55. public Bitmap zoomImage(Bitmap bgimage, int newWidth, int newHeight) {  

  56. // 获取这个图片的宽和高

  57. int width = bgimage.getWidth();  

  58. int height = bgimage.getHeight();  

  59. // 创建操作图片用的matrix对象

  60. Matrix matrix = new Matrix();  

  61. // 计算缩放率,新尺寸除原始尺寸

  62. float scaleWidth = ((float) newWidth) / width;  

  63. float scaleHeight = ((float) newHeight) / height;  

  64. // 缩放图片动作

  65. matrix.postScale(scaleWidth, scaleHeight);  

  66. Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, width, height,  

  67. matrix, true);  

  68. return bitmap;  

  69. }  

  70. 4.绘制带有边框的文字,一般在游戏中起文字的美化作用  

  71. /***

  72. * 绘制带有边框的文字

  73. *

  74. * @param strMsg

  75. * :绘制内容

  76. * @param g

  77. * :画布

  78. * @param paint

  79. * :画笔

  80. * @param setx

  81. * ::X轴起始坐标

  82. * @param sety

  83. * :Y轴的起始坐标

  84. * @param fg

  85. * :前景色

  86. * @param bg

  87. * :背景色

  88. */

  89. publicvoid drawText(String strMsg, Canvas g, Paint paint, int setx,  

  90. int sety, int fg, int bg) {  

  91. paint.setColor(bg);  

  92. g.drawText(strMsg, setx + 1, sety, paint);  

  93. g.drawText(strMsg, setx, sety �C 1, paint);  

  94. g.drawText(strMsg, setx, sety + 1, paint);  

  95. g.drawText(strMsg, setx �C 1, sety, paint);  

  96. paint.setColor(fg);  

  97. g.drawText(strMsg, setx, sety, paint);  

  98. g.restore();  

  99. }  

  100. 5.Android 图片透明度处理代码  

  101. /**

  102. * 图片透明度处理

  103. *

  104. * @param sourceImg

  105. *            原始图片

  106. * @param number

  107. *            透明度

  108. * @return

  109. */

  110. publicstatic Bitmap setAlpha(Bitmap sourceImg, int number) {  

  111. int[] argb = newint[sourceImg.getWidth() * sourceImg.getHeight()];  

  112. sourceImg.getPixels(argb, 0, sourceImg.getWidth(), 0, 0,sourceImg.getWidth(), sourceImg.getHeight());// 获得图片的ARGB值

  113. number = number * 255 / 100;  

  114. for (int i = 0; i < argb.length; i++) {  

  115. argb = (number << 24) | (argb & 0×00FFFFFF);// 修改最高2位的值

  116. }  

  117. sourceImg = Bitmap.createBitmap(argb, sourceImg.getWidth(), sourceImg.getHeight(), Config.ARGB_8888);  

  118. return sourceImg;  

  119. }  

  120. 6.图片翻转  

  121. Resources res = this.getContext().getResources();  

  122. img = BitmapFactory.decodeResource(res, R.drawable.slogo);  

  123. Matrix matrix = new Matrix();  

  124. matrix.postRotate(90);        /*翻转90度*/

  125. int width = img.getWidth();  

  126. int height = img.getHeight();  

  127. r_img = Bitmap.createBitmap(img, 0, 0, width, height, matrix, true);  

1.图片加载方法,方便用户加载图片
/***
* 加载本地图片
* @param context:主运行函数实例
* @param bitAdress:图片地址,一般指向R下的drawable目录
* @return
*/
public final Bitmap CreatImage(Context context, int bitAdress) {
Bitmap bitmaptemp = null;
bitmaptemp = BitmapFactory.decodeResource(context.getResources(),
bitAdress);
return bitmaptemp;
}
2.图片平均分割方法,将大图平均分割为N行N列,方便用户使用
/***
* 图片分割
*
* @param g
* :画布
* @param paint
* :画笔
* @param imgBit
* :图片
* @param x
* :X轴起点坐标
* @param y
* :Y轴起点坐标
* @param w
* :单一图片的宽度
* @param h
* :单一图片的高度
* @param line
* :第几列
* @param row
* :第几行
*/
public final void cuteImage(Canvas g, Paint paint, Bitmap imgBit, int x,
int y, int w, int h, int line, int row) {
g.clipRect(x, y, x + w, h + y);
g.drawBitmap(imgBit, x �C line * w, y �C row * h, paint);
g.restore();
}
3.图片缩放,对当前图片进行缩放处理
/***
* 图片的缩放方法
*
* @param bgimage
* :源图片资源
* @param newWidth
* :缩放后宽度
* @param newHeight
* :缩放后高度
* @return
*/
public Bitmap zoomImage(Bitmap bgimage, int newWidth, int newHeight) {
// 获取这个图片的宽和高
int width = bgimage.getWidth();
int height = bgimage.getHeight();
// 创建操作图片用的matrix对象
Matrix matrix = new Matrix();
// 计算缩放率,新尺寸除原始尺寸
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// 缩放图片动作
matrix.postScale(scaleWidth, scaleHeight);
Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, width, height,
matrix, true);
return bitmap;
}
4.绘制带有边框的文字,一般在游戏中起文字的美化作用
/***
* 绘制带有边框的文字
*
* @param strMsg
* :绘制内容
* @param g
* :画布
* @param paint
* :画笔
* @param setx
* ::X轴起始坐标
* @param sety
* :Y轴的起始坐标
* @param fg
* :前景色
* @param bg
* :背景色
*/
public void drawText(String strMsg, Canvas g, Paint paint, int setx,
int sety, int fg, int bg) {
paint.setColor(bg);
g.drawText(strMsg, setx + 1, sety, paint);
g.drawText(strMsg, setx, sety �C 1, paint);
g.drawText(strMsg, setx, sety + 1, paint);
g.drawText(strMsg, setx �C 1, sety, paint);
paint.setColor(fg);
g.drawText(strMsg, setx, sety, paint);
g.restore();
}
5.Android 图片透明度处理代码
/**
* 图片透明度处理
*
* @param sourceImg
*            原始图片
* @param number
*            透明度
* @return
*/
public static Bitmap setAlpha(Bitmap sourceImg, int number) {
int[] argb = new int[sourceImg.getWidth() * sourceImg.getHeight()];
sourceImg.getPixels(argb, 0, sourceImg.getWidth(), 0, 0,sourceImg.getWidth(), sourceImg.getHeight());// 获得图片的ARGB值
number = number * 255 / 100;
for (int i = 0; i < argb.length; i++) {
argb = (number << 24) | (argb & 0×00FFFFFF);// 修改最高2位的值
}
sourceImg = Bitmap.createBitmap(argb, sourceImg.getWidth(), sourceImg.getHeight(), Config.ARGB_8888);
return sourceImg;
}
6.图片翻转
Resources res = this.getContext().getResources();
img = BitmapFactory.decodeResource(res, R.drawable.slogo);
Matrix matrix = new Matrix();
matrix.postRotate(90);        /*翻转90度*/
int width = img.getWidth();
int height = img.getHeight();
r_img = Bitmap.createBitmap(img, 0, 0, width, height, matrix, true);

Java代码 复制代码 收藏代码 spinner.gif
  1. import android.graphics.Bitmap;  

  2. import android.graphics.Canvas;  

  3. import android.graphics.LinearGradient;  

  4. import android.graphics.Matrix;  

  5. import android.graphics.Paint;  

  6. import android.graphics.PixelFormat;  

  7. import android.graphics.PorterDuffXfermode;  

  8. import android.graphics.Rect;  

  9. import android.graphics.RectF;  

  10. import android.graphics.Bitmap.Config;  

  11. import android.graphics.PorterDuff.Mode;  

  12. import android.graphics.Shader.TileMode;  

  13. import android.graphics.drawable.Drawable;  

  14. /**

  15. *

  16. * @author superdev

  17. * @version 1.0

  18. *

  19. */

  20. publicclass ImageUtil {  

  21. /**

  22. * 放大缩小图片

  23. */

  24. publicstatic Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {  

  25. int width = bitmap.getWidth();  

  26. int height = bitmap.getHeight();  

  27.   Matrix matrix = new Matrix();  

  28. float scaleWidht = ((float) w / width);  

  29. float scaleHeight = ((float) h / height);  

  30.   matrix.postScale(scaleWidht, scaleHeight);  

  31.   Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);  

  32. return newbmp;  

  33. }  

  34. /**

  35. * 将Drawable转化为Bitmap

  36. */

  37. publicstatic Bitmap drawableToBitmap(Drawable drawable) {  

  38. int width = drawable.getIntrinsicWidth();  

  39. int height = drawable.getIntrinsicHeight();  

  40.   Bitmap bitmap = Bitmap.createBitmap(width, height, drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);  

  41.   Canvas canvas = new Canvas(bitmap);  

  42.   drawable.setBounds(0, 0, width, height);  

  43.   drawable.draw(canvas);  

  44. return bitmap;  

  45. }  

  46. /**

  47. * 获得圆角图片的方法

  48. */

  49. publicstatic Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {  

  50.   Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);  

  51.   Canvas canvas = new Canvas(output);  

  52. finalint color = 0xff424242;  

  53. final Paint paint = new Paint();  

  54. final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());  

  55. final RectF rectF = new RectF(rect);  

  56.   paint.setAntiAlias(true);  

  57.   canvas.drawARGB(0, 0, 0, 0);  

  58.   paint.setColor(color);  

  59.   canvas.drawRoundRect(rectF, roundPx, roundPx, paint);  

  60.   paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));  

  61.   canvas.drawBitmap(bitmap, rect, rect, paint);  

  62. return output;  

  63. }  

  64. /**

  65. * 获得带倒影的图片方法

  66. */

  67. publicstatic Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {  

  68. finalint reflectionGap = 4;  

  69. int width = bitmap.getWidth();  

  70. int height = bitmap.getHeight();  

  71.   Matrix matrix = new Matrix();  

  72.   matrix.preScale(1, -1);  

  73.   Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height / 2, width, height / 2, matrix, false);  

  74.   Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height / 2), Config.ARGB_8888);  

  75.   Canvas canvas = new Canvas(bitmapWithReflection);  

  76.   canvas.drawBitmap(bitmap, 0, 0, null);  

  77.   Paint deafalutPaint = new Paint();  

  78.   canvas.drawRect(0, height, width, height + reflectionGap, deafalutPaint);  

  79.   canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);  

  80.   Paint paint = new Paint();  

  81.   LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0, bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP);  

  82.   paint.setShader(shader);  

  83. // Set the Transfer mode to be porter duff and destination in

  84.   paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));  

  85. // Draw a rectangle using the paint with our linear gradient

  86.   canvas.drawRect(0, height, width, bitmapWithReflection.getHeight() + reflectionGap, paint);  

  87. return bitmapWithReflection;  

  88. }  

  89. }  

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.Drawable;
/**
* 
* @author superdev
* @version 1.0
*
*/
public class ImageUtil {

/**
* 放大缩小图片
*/
public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
   int width = bitmap.getWidth();
   int height = bitmap.getHeight();
   Matrix matrix = new Matrix();
   float scaleWidht = ((float) w / width);
   float scaleHeight = ((float) h / height);
   matrix.postScale(scaleWidht, scaleHeight);
   Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
   return newbmp;
}

/**
* 将Drawable转化为Bitmap
*/
public static Bitmap drawableToBitmap(Drawable drawable) {
   int width = drawable.getIntrinsicWidth();
   int height = drawable.getIntrinsicHeight();
   Bitmap bitmap = Bitmap.createBitmap(width, height, drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
   Canvas canvas = new Canvas(bitmap);
   drawable.setBounds(0, 0, width, height);
   drawable.draw(canvas);
   return bitmap;

}

/**
* 获得圆角图片的方法
*/
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {

   Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
   Canvas canvas = new Canvas(output);

   final int color = 0xff424242;
   final Paint paint = new Paint();
   final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
   final RectF rectF = new RectF(rect);

   paint.setAntiAlias(true);
   canvas.drawARGB(0, 0, 0, 0);
   paint.setColor(color);
   canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

   paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
   canvas.drawBitmap(bitmap, rect, rect, paint);

   return output;
}

/**
* 获得带倒影的图片方法
*/
public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {
   final int reflectionGap = 4;
   int width = bitmap.getWidth();
   int height = bitmap.getHeight();

   Matrix matrix = new Matrix();
   matrix.preScale(1, -1);

   Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height / 2, width, height / 2, matrix, false);

   Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height / 2), Config.ARGB_8888);

   Canvas canvas = new Canvas(bitmapWithReflection);
   canvas.drawBitmap(bitmap, 0, 0, null);
   Paint deafalutPaint = new Paint();
   canvas.drawRect(0, height, width, height + reflectionGap, deafalutPaint);

   canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);

   Paint paint = new Paint();
   LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0, bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP);
   paint.setShader(shader);
   // Set the Transfer mode to be porter duff and destination in
   paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
   // Draw a rectangle using the paint with our linear gradient
   canvas.drawRect(0, height, width, bitmapWithReflection.getHeight() + reflectionGap, paint);
   return bitmapWithReflection;
}
}

Java代码 复制代码 收藏代码 spinner.gif
  1. privatebyte[] Bitmap2Bytes(Bitmap bm){  

  2.   ByteArrayOutputStream baos = new ByteArrayOutputStream();  

  3.   bm.compress(Bitmap.CompressFormat.PNG, 100, baos);  

  4. return baos.toByteArray();  

  5. }  

  6. private Bitmap Bytes2Bimap(byte[] b){  

  7. if(b.length!=0){  

  8. return BitmapFactory.decodeByteArray(b, 0, b.length);  

  9.            }  

  10. else {  

  11. returnnull;  

  12.            }  

  13.      }  

  14. /**

  15.     * create the bitmap from a byte array

  16.     *生成水印图片

  17.     * @param src the bitmap object you want proecss

  18.     * @param watermark the water mark above the src

  19.     * @return return a bitmap object ,if paramter's length is 0,return null

  20.     */

  21. private Bitmap createBitmap( Bitmap src, Bitmap watermark )  

  22.    {  

  23.        String tag = "createBitmap";  

  24.        Log.d( tag, "create a new bitmap" );  

  25. if( src == null )  

  26.        {  

  27. returnnull;  

  28.        }  

  29. int w = src.getWidth();  

  30. int h = src.getHeight();  

  31. int ww = watermark.getWidth();  

  32. int wh = watermark.getHeight();  

  33. //create the new blank bitmap

  34.        Bitmap newb = Bitmap.createBitmap( w, h, Config.ARGB_8888 );//创建一个新的和SRC长度宽度一样的位图

  35.        Canvas cv = new Canvas( newb );  

  36. //draw src into

  37.        cv.drawBitmap( src, 0, 0, null );//在 0,0坐标开始画入src

  38. //draw watermark into

  39.        cv.drawBitmap( watermark, w - ww + 5, h - wh + 5, null );//在src的右下角画入水印

  40. //save all clip

  41.        cv.save( Canvas.ALL_SAVE_FLAG );//保存

  42. //store

  43.        cv.restore();//存储

  44. return newb;  

  45.    }  

  46. /** 重新编码Bitmap

  47.   *

  48.   * @param src

  49.   *          需要重新编码的Bitmap

  50.   *

  51.   * @param format

  52.   *          编码后的格式(目前只支持png和jpeg这两种格式)

  53.   *

  54.   * @param quality

  55.   *          重新生成后的bitmap的质量

  56.   *

  57.   * @return

  58.   *          返回重新生成后的bitmap

  59.   */

  60. privatestatic Bitmap codec(Bitmap src, Bitmap.CompressFormat format,  

  61. int quality) {  

  62.            ByteArrayOutputStream os = new ByteArrayOutputStream();  

  63.            src.compress(format, quality, os);              

  64. byte[] array = os.toByteArray();  

  65. return BitmapFactory.decodeByteArray(array, 0, array.length);  

  66.        }  

  67. //Stream转换成Byte

  68. staticbyte[] streamToBytes(InputStream is) {  

  69.      ByteArrayOutputStream os = new ByteArrayOutputStream(1024);  

  70. byte[] buffer = newbyte[1024];  

  71. int len;  

  72. try {  

  73. while ((len = is.read(buffer)) >= 0) {  

  74.             os.write(buffer, 0, len);  

  75.             }  

  76.          } catch (java.io.IOException e) {  

  77.          }  

  78. return os.toByteArray();  

  79. }  

  80. //把View转换成Bitmap

  81. /**

  82.     * 把一个View的对象转换成bitmap

  83.     */

  84. static Bitmap getViewBitmap(View v) {  

  85.        v.clearFocus();  

  86.        v.setPressed(false);  

  87. //能画缓存就返回false

  88. boolean willNotCache = v.willNotCacheDrawing();  

  89.        v.setWillNotCacheDrawing(false);  

  90. int color = v.getDrawingCacheBackgroundColor();  

  91.        v.setDrawingCacheBackgroundColor(0);  

  92. if (color != 0) {  

  93.            v.destroyDrawingCache();  

  94.        }  

  95.        v.buildDrawingCache();  

  96.        Bitmap cacheBitmap = v.getDrawingCache();  

  97. if (cacheBitmap == null) {  

  98.            Log.e(TAG, "failed getViewBitmap(" + v + ")", new RuntimeException());  

  99. returnnull;  

  100.        }  

  101.        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);  

  102. // Restore the view

  103.        v.destroyDrawingCache();  

  104.        v.setWillNotCacheDrawing(willNotCache);  

  105.        v.setDrawingCacheBackgroundColor(color);  

  106. return bitmap;  

  107.    }  

private byte[] Bitmap2Bytes(Bitmap bm){
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
   return baos.toByteArray();
}
private Bitmap Bytes2Bimap(byte[] b){
		    if(b.length!=0){
		    	return BitmapFactory.decodeByteArray(b, 0, b.length);
		    }
		    else {
		    	return null;
		    }
	  }

 /**
     * create the bitmap from a byte array
     *生成水印图片
     * @param src the bitmap object you want proecss
     * @param watermark the water mark above the src
     * @return return a bitmap object ,if paramter's length is 0,return null
     */
    private Bitmap createBitmap( Bitmap src, Bitmap watermark )
    {
        String tag = "createBitmap";
        Log.d( tag, "create a new bitmap" );
        if( src == null )
        {
            return null;
        }
 
        int w = src.getWidth();
        int h = src.getHeight();
        int ww = watermark.getWidth();
        int wh = watermark.getHeight();
        //create the new blank bitmap
        Bitmap newb = Bitmap.createBitmap( w, h, Config.ARGB_8888 );//创建一个新的和SRC长度宽度一样的位图
        Canvas cv = new Canvas( newb );
        //draw src into
        cv.drawBitmap( src, 0, 0, null );//在 0,0坐标开始画入src
        //draw watermark into
        cv.drawBitmap( watermark, w - ww + 5, h - wh + 5, null );//在src的右下角画入水印
        //save all clip
        cv.save( Canvas.ALL_SAVE_FLAG );//保存
        //store
        cv.restore();//存储
        return newb;
    }
   /** 重新编码Bitmap
   * 
   * @param src
   *          需要重新编码的Bitmap
   *
   * @param format
   *          编码后的格式(目前只支持png和jpeg这两种格式)
   *
   * @param quality
   *          重新生成后的bitmap的质量
   *
   * @return
   *          返回重新生成后的bitmap
   */
 private static Bitmap codec(Bitmap src, Bitmap.CompressFormat format,
                                    int quality) {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            src.compress(format, quality, os);            

            byte[] array = os.toByteArray();
            return BitmapFactory.decodeByteArray(array, 0, array.length);
        }

//Stream转换成Byte
static byte[] streamToBytes(InputStream is) {
      ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
      byte[] buffer = new byte[1024];
      int len;
      try {
             while ((len = is.read(buffer)) >= 0) {
             os.write(buffer, 0, len);
             }
          } catch (java.io.IOException e) {

          }
          return os.toByteArray();
}
//把View转换成Bitmap

    /**
     * 把一个View的对象转换成bitmap
     */
    static Bitmap getViewBitmap(View v) {
    	
        v.clearFocus();
        v.setPressed(false);

        //能画缓存就返回false
        boolean willNotCache = v.willNotCacheDrawing();
        v.setWillNotCacheDrawing(false); 
        int color = v.getDrawingCacheBackgroundColor();
        v.setDrawingCacheBackgroundColor(0);
        if (color != 0) {
            v.destroyDrawingCache();
        }
        v.buildDrawingCache();
        Bitmap cacheBitmap = v.getDrawingCache();
        if (cacheBitmap == null) {
            Log.e(TAG, "failed getViewBitmap(" + v + ")", new RuntimeException());
            return null;
        }
        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
        // Restore the view
        v.destroyDrawingCache();
        v.setWillNotCacheDrawing(willNotCache);
        v.setDrawingCacheBackgroundColor(color);
        return bitmap;
    }


Java代码 复制代码 收藏代码 spinner.gif
  1. 读取raw资源文件中的mp3文件,然后通过音乐播放器播放:  

  2. /**

  3.     * 把mp3文件写入卡

  4.     *

  5.     * @param fileName

  6.     *             输出的文件名(全路径)

  7.     * @param context

  8.         *             context对象

  9.     */

  10. privatevoid writeMP3ToSDcard(String fileName, Context context) {  

  11. byte[] buffer = newbyte[1024 * 8];  

  12. int read;  

  13.        BufferedInputStream bin = new BufferedInputStream(context.getResources().openRawResource(R.raw.ring));  

  14. try {  

  15.            BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(fileName));  

  16. while ((read = bin.read(buffer)) > -1) {  

  17.                bout.write(buffer, 0, read);  

  18.            }  

  19.            bout.flush();  

  20.            bout.close();  

  21.            bin.close();  

  22.        } catch (FileNotFoundException e) {  

  23.            e.printStackTrace();  

  24.        } catch (IOException e) {  

  25.            e.printStackTrace();  

  26.        }  

  27.    }  

  28. Intent intent = new Intent();  

  29. intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  

  30. intent.setAction(android.content.Intent.ACTION_VIEW);  

  31. intent.setDataAndType(Uri.fromFile(newFile("XXXXmp3的文件全路径")),"audio/*");  

  32. startActivity(intent);  

读取raw资源文件中的mp3文件,然后通过音乐播放器播放:

	/**
	 * 把mp3文件写入卡
	 * 
	 * @param fileName
	 *             输出的文件名(全路径)
	 * @param context
         *             context对象
	 */
	private void writeMP3ToSDcard(String fileName, Context context) {
		byte[] buffer = new byte[1024 * 8];
		int read;
		BufferedInputStream bin = new BufferedInputStream(context.getResources().openRawResource(R.raw.ring));
		try {
			BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(fileName));
			while ((read = bin.read(buffer)) > -1) {
				bout.write(buffer, 0, read);
			}
			bout.flush();
			bout.close();
			bin.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(newFile("XXXXmp3的文件全路径")),"audio/*");
startActivity(intent);



绘制图像倒影
Java代码 复制代码 收藏代码 spinner.gif
  1. privatevoid

  2. _Init()    

  3. {    

  4.  m_paint = new Paint(Paint.ANTI_ALIAS_FLAG);    

  5.  LinearGradient lg = new LinearGradient(    

  6. 0, 0, 0, m_nShadowH,      

  7. 0xB0FFFFFF, 0x00000000,    

  8.    Shader.TileMode.CLAMP);    

  9.  m_paint.setShader(lg);    

  10.  m_paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.MULTIPLY));    

  11. }    

  12. @Overrideprotectedvoid

  13. onDraw(Canvas canvas)    

  14. {    

  15. super.onDraw(canvas);    

  16. int nX = 0;    

  17. int nY = 20;    

  18.  _DrawNormalImg(canvas, nX, nY);    

  19.  _DrawMirror(canvas, nX, nY);    

  20. }      

  21. privatevoid

  22. _DrawNormalImg(Canvas canvas, int nX, int nY)    

  23. {    

  24.  canvas.save(Canvas.MATRIX_SAVE_FLAG);    

  25.  canvas.translate(nX, nY);        

  26.  m_dw.draw(canvas);    

  27.  canvas.restore();    

  28. }    

  29. privatevoid

  30. _DrawMirror(Canvas canvas, int nX, int nY)    

  31. {    

  32. int nW = m_dw.getIntrinsicWidth();    

  33. int nH = m_dw.getIntrinsicHeight();    

  34. ///////////////////////////////////  

  35. //draw mirror image  

  36.  canvas.save(Canvas.MATRIX_SAVE_FLAG);    

  37.  canvas.scale(1.0f, -1.0f);    

  38.  canvas.translate(nX, -(nY + nH * 2));    

  39.  canvas.clipRect(0, nH, nW, nH - m_nShadowH);    

  40.  m_dw.draw(canvas);    

  41.  canvas.restore();    

  42. //////////////////////////////  

  43. //draw mask  

  44.  canvas.save();    

  45.  canvas.translate(nX, nY + nH);    

  46.  canvas.drawRect(0, 0, nW, m_nShadowH, m_paint);    

  47.  canvas.restore();    

  48. }    


你可能感兴趣的:(android)