將彩色圖轉換爲灰度圖
- /**
- * 將彩色圖轉換爲灰度圖
- * @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;
- }
- /**
- * 將彩色圖轉換爲灰度圖
- * @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;
- }

將一個圖片切割成多個圖片
有種場景,我們想將一個圖片切割成多個圖片。比如我們在開發一個拼圖的遊戲,就首先要對圖片進行切割。
以下是封裝好的兩個類,可以實現圖片的切割。僅供參考和學習。
一個是ImagePiece類,此類保存了一個Bitmap對象和一個標識圖片的順序索引的int變量。
- import android.graphics.Bitmap;
- public class ImagePiece {
- public int index = 0;
- public Bitmap bitmap = null;
- }
- import android.graphics.Bitmap;
- public class ImagePiece {
- public int index = 0;
- public Bitmap bitmap = null;
- }
一個是ImageSplitter類,有一個靜態方法split,傳入的參數是要切割的Bitmap對象,和橫向和豎向的切割片數。比如傳入的是3、3,則橫豎向都切割成3片,最終會將整個圖片切割成3X3=9片。
- 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;
- }
-
- }
- 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()。
- 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);
- 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源碼:
- /*
- * 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;
- }
- }
- /*
- * 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;
- }
- }
實現鏡像方法:
- //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);
-
- }
- //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);
-
- }
圖片Url保存爲位圖並進行縮放操作
- //圖片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);
-
- }
- //圖片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);
-
- }
圖片處理操作——切割,縮放,邊框,透明度
- 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 – line * w, y – 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 – 1, paint);
- g.drawText(strMsg, setx, sety + 1, paint);
- g.drawText(strMsg, setx – 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);
- 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 – line * w, y – 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 – 1, paint);
- g.drawText(strMsg, setx, sety + 1, paint);
- g.drawText(strMsg, setx – 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代碼

- 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;
- }
- }
- 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;
- }
- }
- 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;
- }
- 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;
- }
讀取raw資源文件中的mp3文件,然後通過音樂播放器播放:
- 讀取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 = newBufferedInputStream(context.getResources().openRawResource(R.raw.ring));
- try {
- BufferedOutputStream bout = new BufferedOutputStream(newFileOutputStream(fileName));
- while ((read = bin.read(buffer)) > -1) {
- bout.write(buffer, 0, read);
- }
- bout.flush();
- bout.close();