android图片处理方法
1、图标加灰色过滤;
2、android的图片资源默认是静态的,单实例;如果两个IM好友的头像一样,最简单的都是用的软件自带头像,有一个在线,一个离线,直接改变头像的灰度,则两个用户的头像都会变灰或者在线,答案是:Drawable.mutate()。
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);
//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);
}
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;
}
读取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代码 收藏代码
private void
_Init()
{
m_paint = new Paint(Paint.ANTI_ALIAS_FLAG);
LinearGradient lg = new LinearGradient(
0, 0, 0, m_nShadowH,
0xB0FFFFFF, 0x00000000,
Shader.TileMode.CLAMP);
m_paint.setShader(lg);
m_paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.MULTIPLY));
}
@Override protected void
onDraw(Canvas canvas)
{
super.onDraw(canvas);
int nX = 0;
int nY = 20;
_DrawNormalImg(canvas, nX, nY);
_DrawMirror(canvas, nX, nY);
}
private void
_DrawNormalImg(Canvas canvas, int nX, int nY)
{
canvas.save(Canvas.MATRIX_SAVE_FLAG);
canvas.translate(nX, nY);
m_dw.draw(canvas);
canvas.restore();
}
private void
_DrawMirror(Canvas canvas, int nX, int nY)
{
int nW = m_dw.getIntrinsicWidth();
int nH = m_dw.getIntrinsicHeight();
///////////////////////////////////
//draw mirror image
canvas.save(Canvas.MATRIX_SAVE_FLAG);
canvas.scale(1.0f, -1.0f);
canvas.translate(nX, -(nY + nH * 2));
canvas.clipRect(0, nH, nW, nH - m_nShadowH);
m_dw.draw(canvas);
canvas.restore();
//////////////////////////////
//draw mask
canvas.save();
canvas.translate(nX, nY + nH);
canvas.drawRect(0, 0, nW, m_nShadowH, m_paint);
canvas.restore();
}
在 Photoshop 中,做鏡像特效的第二步是要對這翻轉的圖片,加個由灰到黑的漸層 mask。
在 Android 中,要畫漸層色,那就一定得用 LinearGradient 這個類別。至於要對背景圖加上個 mask,就請參考一下 Paint 的 setXfermode() 函式。_Init() 這個函式,就是負責生成一個由灰到黑漸層 mask 的 m_paint 物件。
http://blog.csdn.net/Android_Tutor/archive/2010/11/02/5981753.aspx
- Final_Report.pdf (820.1 KB)
尽
量不要使用setImageBitmap或setImageResource或BitmapFactory.decodeResource来设置一张大
图,因为这些函数在完成decode后,最终都是通过java层的createBitmap来完成的,需要消耗更多内存。
因此,改用先通过BitmapFactory.decodeStream方法,创建出一个bitmap,再将其设为ImageView的 source,decodeStream最大的秘密在于其直接调用JNI>>nativeDecodeAsset()来完成decode,无 需再使用java层的createBitmap,从而节省了java层的空间。
因此,改用先通过BitmapFactory.decodeStream方法,创建出一个bitmap,再将其设为ImageView的 source,decodeStream最大的秘密在于其直接调用JNI>>nativeDecodeAsset()来完成decode,无 需再使用java层的createBitmap,从而节省了java层的空间。
如果在读取时加上图片的Config参数,可以跟有效减少加载的内存,从而跟有效阻止抛out of Memory异常
另外,decodeStream直接拿的图片来读取字节码了, 不会根据机器的各种分辨率来自动适应, 使用了decodeStream之后,需要在hdpi和mdpi,ldpi中配置相应的图片资源, 否则在不同分辨率机器上都是同样大小(像素点数量),显示出来的大小就不对了。
1. InputStream is = this.getResources().openRawResource(R.drawable.pic1);
BitmapFactory.Options options=new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inSampleSize = 10; //width,hight设为原来的十分一
Bitmap btp =BitmapFactory.decodeStream(is,null,options);
2. if(!bmp.isRecycle() ){
bmp.recycle() //回收图片所占的内存
system.gc() //提醒系统及时回收
}
以下奉上自己写的一个方法:
int phSize;
float PIX_SCALE;
PIX_SCALE = this.getResources().getDisplayMetrics().density;
phSize = (PHO_DIP * (int) (PIX_SCALE + 0.5f));
public Drawable scale(File file) {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.RGB_565;
opt.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file.getAbsolutePath(), opt);
opt.inJustDecodeBounds = false;
if (opt.outWidth > opt.outHeight) {
opt.inSampleSize = opt.outWidth / phSize;
;
} else {
opt.inSampleSize = opt.outHeight / phSize;
}
Bitmap b = BitmapFactory.decodeFile(file.getAbsolutePath(), opt);
Drawable d = new BitmapDrawable(ManagerActivity.this.getResources(), b);
return d;
}
ZoomControls控件是一个可以缩放但控件,效果如下图
以下是它但一些主要但方法
hasFocus ():判断焦点
hide ():隐藏
onTouchEvent (MotionEvent event):现这个方法来处理触摸屏移动事件
setIsZoomInEnabled (boolean isEnabled):是否允许放大
setIsZoomOutEnabled (boolean isEnabled):是否允许缩小
setOnZoomInClickListener (View.OnClickListener listener):注册放大监听器
setOnZoomOutClickListener (View.OnClickListener listener):注册缩小监听器
setZoomSpeed (long speed):设置缩放速度
show ():显示
这里面,如果将setIsZoomInEnabled()方法设置为false,那么这个放大的按钮就变成了灰色,不能用了,其实这个控件就是两个按钮而已,只是有外观,没有功能,如果你要放大图片或者缩小图片,还是要在监听事件中实现
开始看代码
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/layout1"
>
<ImageView
android:id="@+id/imgview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/yuanyuan"
/>
<ZoomControls
android:id="@+id/zoomcontrol"
android:layout_gravity="bottom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
ZoomExampleActivity.java
效果如下: