import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
publicclass ImageUtil {
privatestaticfinal String SDCARD_CACHE_IMG_PATH = Environment
.getExternalStorageDirectory().getPath() + "/images/";
/**
* 保存图片到SD卡
*
* @param imagePath
* @param buffer
* @throws IOException
*/
publicstaticvoid saveImage(String imagePath, byte[] buffer)
throws IOException {
File f = new File(imagePath);
if (f.exists()) {
return;
} else {
File parentFile = f.getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs();
}
f.createNewFile();
FileOutputStream fos = new FileOutputStream(imagePath);
fos.write(buffer);
fos.flush();
fos.close();
}
}
/**
* 从SD卡加载图片
*
* @param imagePath
* @return
*/
publicstatic Bitmap getImageFromLocal(String imagePath) {
File file = new File(imagePath);
if (file.exists()) {
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
file.setLastModified(System.currentTimeMillis());
return bitmap;
}
returnnull;
}
/**
* Bitmap转换到Byte[]
*
* @param bm
* @return
*/
publicstaticbyte[] bitmap2Bytes(Bitmap bm) {
ByteArrayOutputStream bas = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, bas);
return bas.toByteArray();
}
/**
* 从本地或者服务端加载图片
*
* @return
* @throws IOException
*/
publicstatic Bitmap loadImage(final String imagePath, final String imgUrl,
final ImageCallback callback) {
Bitmap bitmap = getImageFromLocal(imagePath);
if (bitmap != null) {
return bitmap;
} else {// 从网上加载
final Handler handler = new Handler() {
@Override
publicvoid handleMessage(Message msg) {
if (msg.obj != null) {
Bitmap bitmap = (Bitmap) msg.obj;
callback.loadImage(bitmap, imagePath);
}
}
};
Runnable runnable = new Runnable() {
@Override
publicvoid run() {
try {
URL url = new URL(imgUrl);
Log.e("图片加载", imgUrl);
URLConnection conn = url.openConnection();
conn.connect();
BufferedInputStream bis = new BufferedInputStream(
conn.getInputStream(), 8192);
Bitmap bitmap = BitmapFactory.decodeStream(bis);
// 保存文件到sd卡
saveImage(imagePath, bitmap2Bytes(bitmap));
Message msg = handler.obtainMessage();
msg.obj = bitmap;
handler.sendMessage(msg);
} catch (IOException e) {
Log.e(ImageUtil.class.getName(), "保存图片到本地存储卡出错!");
}
}
};
// ThreadPoolManager.getInstance().addTask(runnable);
}
returnnull;
}
// 返回图片存到sd卡的路径
publicstatic String getCacheImgPath() {
returnSDCARD_CACHE_IMG_PATH;
}
/**
* 将图片保存到相应目录中
*
* @param context
* @param bitmap
* @param fileName
*/
publicsynchronizedstaticvoid savaImage(Context context, Bitmap bitmap,
String dir, String fileName) {
File sdDir = new File("/sdcard/");
if (sdDir.exists() && sdDir.canWrite()) {
File uadDir = new File(sdDir.getAbsolutePath() + "/cyej/" + dir);
uadDir.mkdir();
if (uadDir.exists() && uadDir.canWrite()) {
File file = new File(uadDir.getAbsolutePath() + "/" + fileName);
try {
file.createNewFile();
} catch (IOException e) {
Log.e("ImageUtil", "error creating file", e);
}
if (file.exists() && file.canWrite()) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 50, fos);
} catch (FileNotFoundException e) {
Log.e("ImageUtil", "ERROR", e);
} catch (Exception e) {
Log.e("ImageUtil", "ERROR", e);
} finally {
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
// swallow
}
}
}
} else {
Log.e("ImageUtil", "error writing to file");
}
}
}
recyleBitmapMemory(bitmap);
}
/**
* 从相应目录中获取图片
*
* @param fileName
* @param context
* @return
*/
publicstatic Bitmap getImage(String dir, String fileName, Context context) {
File rFile = new File("/sdcard/cyej/" + dir + "/" + fileName);
if (rFile.exists() && rFile.canRead()) {
FileInputStream fis = null;
try {
fis = new FileInputStream(rFile);
BitmapDrawable bd = new BitmapDrawable(fis);
Bitmap newBitmap = bd.getBitmap();
return newBitmap;
} catch (IOException e) {
Log.e("ImageUtil", e.getMessage(), e);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
// swallow
}
}
}
}
returnnull;
}
/**
* 获取相应目录中所有图片
*
* @param fileName
* @param context
* @return
*/
publicstatic ArrayList<Bitmap> getAllimagefromdir(String dir) {
ArrayList<Bitmap> listbitmap = new ArrayList<Bitmap>();
File rFile = new File("/sdcard/cyej/" + dir);
String[] filelist = rFile.list();
for (int i = 0; i < filelist.length; i++) {
File readfile = new File(rFile.getAbsolutePath() + "/"
+ filelist[i]);
if (readfile.getName().indexOf(".txt") == -1) {
FileInputStream fis = null;
try {
fis = new FileInputStream(readfile);
BitmapDrawable bd = new BitmapDrawable(fis);
Bitmap newBitmap = bd.getBitmap();
listbitmap.add(newBitmap);
} catch (IOException e) {
Log.e("ImageUtil", e.getMessage(), e);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return listbitmap;
}
/**
* 将图片转换成圆角图片
*
* @param bitmap
* @return
*/
publicstatic Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
finalint color = 0xff424242;
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
finalfloat roundPx = 6;
paint.setAntiAlias(true);
paint.setColor(color);
canvas.drawARGB(0, 0, 0, 0);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new android.graphics.PorterDuffXfermode(
android.graphics.PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, 0, 0, paint);
return output;
}
/***
* 图片的缩放方法
*
* @param bgimage
* :源图片资源
* @param newWidth
* :缩放后宽度
* @param newHeight
* :缩放后高度
* @return
*/
publicstatic Bitmap zoomImage(Bitmap bgimage) {
int newHeight = 0;
if (bgimage.getWidth() > 460) {
newHeight = bgimage.getHeight() / bgimage.getWidth() * 460;
} else {
return bgimage;
}
// 获取这个图片的宽和高
int width = bgimage.getWidth();
int height = bgimage.getHeight();
// 创建操作图片用的matrix对象
Matrix matrix = new Matrix();
// 计算缩放率,新尺寸除原始尺寸
float scaleWidth = ((float) 460) / width;
float scaleHeight = ((float) newHeight) / height;
// 缩放图片动作
matrix.postScale(scaleWidth, scaleHeight);
Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, width, height,
matrix, true);
return bitmap;
}
/**
* 读取本地图片资源
*
* @param imgStr
* 图片路径
* @param context
* Activity
* @return
*/
publicstatic BitmapDrawable getBitmapDrawable(String imgStr,
Context context) {
Bitmap bmp = null;
try {
bmp = BitmapFactory.decodeStream(context.getAssets().open(imgStr));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BitmapDrawable bitmapdraw = new BitmapDrawable(bmp);
return bitmapdraw;
}
/**
* 把drawable强制转换成Bitmap
*
* @param drawable
* @return
*/
publicstatic Bitmap drawableToBitmap(Drawable drawable) {
Bitmap bitmap = Bitmap
.createBitmap(
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
// canvas.setBitmap(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}
// 获得带倒影的图片方法
publicstatic Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {
finalint 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;
}
publicstatic String md5(String paramString) {
String returnStr;
try {
MessageDigest localMessageDigest = MessageDigest.getInstance("MD5");
localMessageDigest.update(paramString.getBytes());
returnStr = byteToHexString(localMessageDigest.digest());
return returnStr;
} catch (Exception e) {
return paramString;
}
}
/**
* 将指定byte数组转换成16进制字符串
*
* @param b
* @return
*/
publicstatic String byteToHexString(byte[] b) {
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
hexString.append(hex.toUpperCase());
}
return hexString.toString();
}
/**
* 回收位图所占的空间大小
*
* @param bitmap
*/
publicstaticvoid recyleBitmapMemory(Bitmap bitmap) {
if (null != bitmap && !bitmap.isRecycled()) {
bitmap.recycle();
}
}
publicinterface ImageCallback {
publicvoid loadImage(Bitmap bitmap, String imagePath);
}
}