拍照(从本地获取存储在SD卡中)

public class UploadingDataActivity extends Activity {
private static final int CAMERA_WITH_DATA = 3023;
/* 用来标识请求gallery的activity */
private static final int PHOTO_PICKED_WITH_DATA = 3021;
public static final int RESULT_CODE = 3333;


/* 拍照的照片存储位置 */
private static final File PHOTO_DIR = new File(
Environment.getExternalStorageDirectory(), "/PHB/Camera");
private File mCurrentPhotoFile;// 照相机拍照得到的图片
private String imgPath = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uploading_data);
doTakePhoto();
}


/**
* 拍照
*/
private void doTakePhoto() {
if (!SDCardUtils.isSDCardEnable()) {
showToast(UploadingDataActivity.this, "没有SDCard");
// Toast.makeText(this, "没有SDCard", Toast.LENGTH_LONG).show();
return;
}
try {
PHOTO_DIR.mkdirs();// 创建照片的存储目录
mCurrentPhotoFile = new File(PHOTO_DIR, getPhotoFileName());// 给新照的照片文件命名
final Intent intent = getTakePickIntent(mCurrentPhotoFile);
startActivityForResult(intent, CAMERA_WITH_DATA);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "没有照相机程序", Toast.LENGTH_LONG).show();
}
}


/**
* 从图库选择
*/
protected void doPickPhotoFromGallery() {
try {
PHOTO_DIR.mkdirs();
mCurrentPhotoFile = new File(PHOTO_DIR, getPhotoFileName());
final Intent intent = getPhotoPickIntent(mCurrentPhotoFile);
startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "not find photo", Toast.LENGTH_LONG).show();
}
}


public static Intent getPhotoPickIntent(File f) {
Intent intent = new Intent("android.intent.action.PICK");
intent.setDataAndType(MediaStore.Images.Media.INTERNAL_CONTENT_URI,
"image/*");
return intent;
}


/**
* 用当前时间给取得的图片命名
*
*/
public static String getPhotoFileName() {
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat dateFormat = new SimpleDateFormat(
"'IMG'_yyyyMMdd_HHmmss");
return dateFormat.format(date) + ".jpg";
}


public static Intent getTakePickIntent(File f) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
return intent;
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);


if (requestCode == 111) {
if (resultCode == 112) {
String name = data.getStringExtra("name");
// edt_name.setText(name);


}
}


dealWithUploadImageOnActivityResult(requestCode, resultCode, data);
}


/**
* 处理上传图片
*
* @param requestCode
* @param resultCode
* @param data
*/
private void dealWithUploadImageOnActivityResult(int requestCode,
int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case PHOTO_PICKED_WITH_DATA:// 从相册里面返回
try {
if (data != null) {
ContentResolver cr = this.getContentResolver();
imgPath = ImageUtil.getUriString(data.getData(), cr);
showThumbnails(imgPath);
}
} catch (Exception e1) {
e1.printStackTrace();
}
break;
case CAMERA_WITH_DATA:// 从相机里面返回
try {
imgPath = mCurrentPhotoFile.getPath();
showThumbnails(imgPath);
} catch (Exception e) {
e.printStackTrace();
// Toast.makeText(this, "拍摄失败,请重新拍摄",
// Toast.LENGTH_LONG).show();
showToast(this, "拍摄失败,请重新拍摄");
}
break;


}
}
}


ImageView mIvPhoto;


/**
* 显示缩略图
*
* @param imgPath
*/
private void showThumbnails(String imgPath) {
mIvPhoto.setImageBitmap(compressImg(imgPath));
saveBefore(imgPath);
setPhoto();
Log.e("imgPath", imgPath);
}


private Bitmap compressImg(String imgPath) {
if (StringUtils.isNotEmpty(imgPath)) {
Bitmap resizeBitmap = ImageUtil.parseHeadBitmapToLittle(imgPath);
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ExifInterface sourceExif = new ExifInterface(imgPath);
int result = sourceExif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
int rotate = 0;
switch (result) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
}


if (resizeBitmap != null) {
if (rotate > 0) {
Matrix matrix = new Matrix();
matrix.setRotate(rotate);


Bitmap rotateBitmap = Bitmap.createBitmap(resizeBitmap,
0, 0, resizeBitmap.getWidth(),
resizeBitmap.getHeight(), matrix, true);
if (rotateBitmap != null) {
resizeBitmap.recycle();
resizeBitmap = rotateBitmap;
}
}
resizeBitmap
.compress(Bitmap.CompressFormat.JPEG, 100, baos);
int options = 100;
while (baos.toByteArray().length > 50 * 1024) { // 循环判断如果压缩后图片是否大于200K,大于继续压缩
baos.reset();// 重置baos即清空baos
resizeBitmap.compress(Bitmap.CompressFormat.JPEG,
options, baos);// 这里压缩options%,把压缩后的数据存放到baos中
options -= 10;// 每次都减少10
}
return resizeBitmap;


}


} catch (OutOfMemoryError e) {
System.gc();
} catch (IOException e) {
e.printStackTrace();
}
} else {
showToast(UploadingDataActivity.this, "图片路径为空");
}
return null;
}


private String time;
private boolean re = true;
private boolean carme = false;


@Override
protected void onPause() {
super.onPause();
long millis = System.currentTimeMillis();
share.setValue("timePause", millis + "");
share.setValue("actName", this.getClass().getName().toString() + "");
}


@Override
protected void onRestart() {
super.onRestart();
long millis = System.currentTimeMillis();
String value = share.getValue("timePause");
long millis2 = 0;
if (StringUtils.isNotEmpty(value)) {
millis2 = Long.parseLong(value);
}
LogUtils.e(time + "||" + (millis2 - millis) + "||" + value);


String actName = share.getValue("actName");
if (actName.equals(this.getClass().getName().toString())) {
if (time == null || time.equals("0")) {
if (re && !carme) {
startActivity(GestureVerifyActivity.class);
re = false;
}


} else {
if (re && !carme) {
if ((millis - millis2) >= 60) {
startActivity(GestureVerifyActivity.class);
re = false;
}
}
}
}
}


private void startActivity(Class<GestureVerifyActivity> class1) {
// TODO Auto-generated method stub
startActivity(new Intent(UploadingDataActivity.this, class1));
}


/**
* 设置公共标题和返回事件
*
* @param title
*/
public void setTitle(String title) {
TextView titleT = (TextView) findViewById(R.id.tv_title);
titleT.setText(title);
TextView backBtn = (TextView) findViewById(R.id.iv_titleback);
backBtn.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View v) {
finish();
}
});
}


private void showToast(UploadingDataActivity uploadingDataActivity,
String string) {
// TODO Auto-generated method stub
Toast.makeText(uploadingDataActivity, string, 1).show();
}


/**
* 读取路径中的图片,然后将其转化为缩放后的bitmap
*
* @param path
*/
public String saveBefore(String path) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
// 获取这个图片的宽和高
Bitmap bitmap = BitmapFactory.decodeFile(path, options); // 此时返回bm为空
options.inJustDecodeBounds = false;
// 计算缩放比
int be = (int) (options.outHeight / (float) 200);
if (be <= 0)
be = 1;
options.inSampleSize = 4; // 图片长宽各缩小至四分之一
// 重新读入图片,注意这次要把options.inJustDecodeBounds 设为 false哦
bitmap = BitmapFactory.decodeFile(path, options);
// savePNG_After(bitmap,path);
return saveJPGE_After(bitmap, path);
}


/**
* 保存图片为JPEG
*
* @param bitmap
* @param path
*/
public String saveJPGE_After(Bitmap bitmap, String path) {
File file = new File(path);
try {
FileOutputStream out = new FileOutputStream(file);
if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
out.flush();
out.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return path;
}
}
public class UploadingDataActivity extends Activity {


 private static final int CAMERA_WITH_DATA = 3023;
/* 用来标识请求gallery的activity */
private static final int PHOTO_PICKED_WITH_DATA = 3021;
public static final int RESULT_CODE = 3333;


/* 拍照的照片存储位置 */
private static final File PHOTO_DIR = new File(
Environment.getExternalStorageDirectory(), "/PHB/Camera");
private File mCurrentPhotoFile;// 照相机拍照得到的图片
private String imgPath = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uploading_data);
doTakePhoto();
}

   

/**
* 拍照
*/
private void doTakePhoto() {
if (!SDCardUtils.isSDCardEnable()) {
showToast(UploadingDataActivity.this, "没有SDCard");
// Toast.makeText(this, "没有SDCard", Toast.LENGTH_LONG).show();
return;
}
try {
PHOTO_DIR.mkdirs();// 创建照片的存储目录
mCurrentPhotoFile = new File(PHOTO_DIR, getPhotoFileName());// 给新照的照片文件命名
final Intent intent = getTakePickIntent(mCurrentPhotoFile);
startActivityForResult(intent, CAMERA_WITH_DATA);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "没有照相机程序", Toast.LENGTH_LONG).show();
}
}


/**
* 从图库选择
*/
protected void doPickPhotoFromGallery() {
try {
PHOTO_DIR.mkdirs();
mCurrentPhotoFile = new File(PHOTO_DIR, getPhotoFileName());
final Intent intent = getPhotoPickIntent(mCurrentPhotoFile);
startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "not find photo", Toast.LENGTH_LONG).show();
}
}


public static Intent getPhotoPickIntent(File f) {
Intent intent = new Intent("android.intent.action.PICK");
intent.setDataAndType(MediaStore.Images.Media.INTERNAL_CONTENT_URI,
"image/*");
return intent;
}


/**
* 用当前时间给取得的图片命名

*/
public static String getPhotoFileName() {
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat dateFormat = new SimpleDateFormat(
"'IMG'_yyyyMMdd_HHmmss");
return dateFormat.format(date) + ".jpg";
}


public static Intent getTakePickIntent(File f) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
return intent;
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);


if (requestCode == 111) {
if (resultCode == 112) {
String name = data.getStringExtra("name");
// edt_name.setText(name);


}
}


dealWithUploadImageOnActivityResult(requestCode, resultCode, data);
}


/**
* 处理上传图片

* @param requestCode
* @param resultCode
* @param data
*/
private void dealWithUploadImageOnActivityResult(int requestCode,
int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case PHOTO_PICKED_WITH_DATA:// 从相册里面返回
try {
if (data != null) {
ContentResolver cr = this.getContentResolver();
imgPath = ImageUtil.getUriString(data.getData(), cr);
showThumbnails(imgPath);
}
} catch (Exception e1) {
e1.printStackTrace();
}
break;
case CAMERA_WITH_DATA:// 从相机里面返回
try {
imgPath = mCurrentPhotoFile.getPath();
showThumbnails(imgPath);
} catch (Exception e) {
e.printStackTrace();
// Toast.makeText(this, "拍摄失败,请重新拍摄",
// Toast.LENGTH_LONG).show();
showToast(this, "拍摄失败,请重新拍摄");
}
break;


}
}
}


ImageView mIvPhoto;


/**
* 显示缩略图

* @param imgPath
*/
private void showThumbnails(String imgPath) {
mIvPhoto.setImageBitmap(compressImg(imgPath));
saveBefore(imgPath);
setPhoto();
Log.e("imgPath", imgPath);
}


private Bitmap compressImg(String imgPath) {
if (StringUtils.isNotEmpty(imgPath)) {
Bitmap resizeBitmap = ImageUtil.parseHeadBitmapToLittle(imgPath);
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ExifInterface sourceExif = new ExifInterface(imgPath);
int result = sourceExif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
int rotate = 0;
switch (result) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
}


if (resizeBitmap != null) {
if (rotate > 0) {
Matrix matrix = new Matrix();
matrix.setRotate(rotate);


Bitmap rotateBitmap = Bitmap.createBitmap(resizeBitmap,
0, 0, resizeBitmap.getWidth(),
resizeBitmap.getHeight(), matrix, true);
if (rotateBitmap != null) {
resizeBitmap.recycle();
resizeBitmap = rotateBitmap;
}
}
resizeBitmap
.compress(Bitmap.CompressFormat.JPEG, 100, baos);
int options = 100;
while (baos.toByteArray().length > 50 * 1024) { // 循环判断如果压缩后图片是否大于200K,大于继续压缩
baos.reset();// 重置baos即清空baos
resizeBitmap.compress(Bitmap.CompressFormat.JPEG,
options, baos);// 这里压缩options%,把压缩后的数据存放到baos中
options -= 10;// 每次都减少10
}
return resizeBitmap;


}


} catch (OutOfMemoryError e) {
System.gc();
} catch (IOException e) {
e.printStackTrace();
}
} else {
showToast(UploadingDataActivity.this, "图片路径为空");
}
return null;
}


private String time;
private boolean re = true;
private boolean carme = false;


@Override
protected void onPause() {
super.onPause();
long millis = System.currentTimeMillis();
share.setValue("timePause", millis + "");
share.setValue("actName", this.getClass().getName().toString() + "");
}


@Override
protected void onRestart() {
super.onRestart();
long millis = System.currentTimeMillis();
String value = share.getValue("timePause");
long millis2 = 0;
if (StringUtils.isNotEmpty(value)) {
millis2 = Long.parseLong(value);
}
LogUtils.e(time + "||" + (millis2 - millis) + "||" + value);


String actName = share.getValue("actName");
if (actName.equals(this.getClass().getName().toString())) {
if (time == null || time.equals("0")) {
if (re && !carme) {
startActivity(GestureVerifyActivity.class);
re = false;
}


} else {
if (re && !carme) {
if ((millis - millis2) >= 60) {
startActivity(GestureVerifyActivity.class);
re = false;
}
}
}
}
}


private void startActivity(Class<GestureVerifyActivity> class1) {
// TODO Auto-generated method stub
startActivity(new Intent(UploadingDataActivity.this, class1));
}


/**
* 设置公共标题和返回事件

* @param title
*/
public void setTitle(String title) {
TextView titleT = (TextView) findViewById(R.id.tv_title);
titleT.setText(title);
TextView backBtn = (TextView) findViewById(R.id.iv_titleback);
backBtn.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View v) {
finish();
}
});
}


private void showToast(UploadingDataActivity uploadingDataActivity,
String string) {
// TODO Auto-generated method stub
Toast.makeText(uploadingDataActivity, string, 1).show();
}


/**
* 读取路径中的图片,然后将其转化为缩放后的bitmap

* @param path
*/
public String saveBefore(String path) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
// 获取这个图片的宽和高
Bitmap bitmap = BitmapFactory.decodeFile(path, options); // 此时返回bm为空
options.inJustDecodeBounds = false;
// 计算缩放比
int be = (int) (options.outHeight / (float) 200);
if (be <= 0)
be = 1;
options.inSampleSize = 4; // 图片长宽各缩小至四分之一
// 重新读入图片,注意这次要把options.inJustDecodeBounds 设为 false哦
bitmap = BitmapFactory.decodeFile(path, options);
// savePNG_After(bitmap,path);
return saveJPGE_After(bitmap, path);
}


/**
* 保存图片为JPEG

* @param bitmap
* @param path
*/
public String saveJPGE_After(Bitmap bitmap, String path) {
File file = new File(path);
try {
FileOutputStream out = new FileOutputStream(file);
if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
out.flush();
out.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return path;
}
}




package com.phb.puhuibao.utils;
import java.io.File;
import android.os.Environment;
import android.os.StatFs;


/**
 * SD卡相关的辅助类
 * 
 * @author zhy
 * 
 */
public class SDCardUtils
{
private SDCardUtils()
{
/* cannot be instantiated */
throw new UnsupportedOperationException("cannot be instantiated");
}
/**
* 判断SDCard是否可用

* @return
*/
public static boolean isSDCardEnable()
{
return Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
}
/**
* 获取SD卡路径

* @return
*/
public static String getSDCardPath()
{
return Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator;
}


/**
* 获取SD卡的剩余容量 单位byte

* @return
*/
public static long getSDCardAllSize()
{
if (isSDCardEnable())
{
StatFs stat = new StatFs(getSDCardPath());
// 获取空闲的数据块的数量
long availableBlocks = (long) stat.getAvailableBlocks() - 4;
// 获取单个数据块的大小(byte)
long freeBlocks = stat.getAvailableBlocks();
return freeBlocks * availableBlocks;
}
return 0;
}


/**
* 获取指定路径所在空间的剩余可用容量字节数,单位byte

* @param filePath
* @return 容量字节 SDCard可用空间,内部存储可用空间
*/
public static long getFreeBytes(String filePath)
{
// 如果是sd卡的下的路径,则获取sd卡可用容量
if (filePath.startsWith(getSDCardPath()))
{
filePath = getSDCardPath();
} else
{// 如果是内部存储的路径,则获取内存存储的可用容量
filePath = Environment.getDataDirectory().getAbsolutePath();
}
StatFs stat = new StatFs(filePath);
long availableBlocks = (long) stat.getAvailableBlocks() - 4;
return stat.getBlockSize() * availableBlocks;
}


/**
* 获取系统存储路径

* @return
*/
public static String getRootDirectoryPath()
{
return Environment.getRootDirectory().getAbsolutePath();
}
}





package com.phb.puhuibao.utils;


import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
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.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;


import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader.TileMode;
import android.net.Uri;


import com.lidroid.xutils.util.LogUtils;


/**
 * 图片工具类.
 */
public class ImageUtil {
public static final String BASEPICPATH = CoreConstants.BASEPICPATH;
public static final String DOWNLOADPATH = CoreConstants.DOWNLOADPATH;
private static Map<String, Bitmap> map = new HashMap<String, Bitmap>();


static {
File f = new File(BASEPICPATH);
if (!f.exists()) {
f.mkdirs();
}
File f2 = new File(DOWNLOADPATH);
if (!f2.exists()) {
f2.mkdirs();
}
}


/**
* 获取图片. 首先从内存里取图片,没有的话 从本地sdcard取图片并保存在map里,
* 本地没有图片的话, 从网络上把图片取下来,保存在sdcard上,在保存在map里
* @param fileUrl 图片网络地址
* @return bitmap对象
*/
public static Bitmap getImage(String fileUrl) {
try {
String filePath = BASEPICPATH + filterPath(fileUrl);
// 首先从内存里取图片
Bitmap bitmap = map.get(filePath);
if (bitmap != null) {
LogUtils.e("getImage from map");
return bitmap;
}


// 从本地sdcard取图片
if (new File(filePath).exists()) {
bitmap = BitmapFactory.decodeFile(filePath);
put(filePath, bitmap);
LogUtils.e("getImage from sdcard   " + filePath);
return bitmap;
}


// 从网络上去图片,并保存在本地,并存储在map里
bitmap = returnBitMap(fileUrl);
if (bitmap != null) {
LogUtils.e("getImage from network");
put(filePath, bitmap);
saveBitmap(bitmap, BASEPICPATH, filterPath(fileUrl));
}
return bitmap;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}


private static void put(String key, Bitmap value) {
Object s[] = map.keySet().toArray();
if (map.size() < 100) {
map.put(key, value);
} else {
map.remove(s[0]);


if (!map.get(key).isRecycled()) {
map.get(key).recycle(); //回收图片所占的内存
}
map.put(key, value);
}


}


/**
* 获取图片. 从本地sdcard取图片,本地没有图片的话 从网络上把图片取下来,保存在sdcard上
* @param fileUrl   图片网络地址
* @return 文件本地路径
*/
public static String getImagePath(Context context, String fileUrl) {
try {
String filePath = BASEPICPATH + filterPath(fileUrl);
// 从本地sdcard取图片
if (new File(filePath).exists()) {
return filePath;
}


String[] bool=null;
// 从网络上把图片取下来,保存在sdcard上,在保存在map里
// String[] bool = HttpClientUtil.download(context, fileUrl);
if (bool != null) {
return filePath;
} else {
return null;
}
} catch (Exception e) {
return null;
}
}


/**
* 下载网络图片.
* @param fileUrl 图片地址
* @param fileName 图片名称
*/
public static void saveImage(final String fileUrl, final String fileName) {
new Thread() {
@Override
public void run() {
Bitmap b = returnBitMap(fileUrl);
try {
String type = contain(fileUrl);
saveBitmap(b, DOWNLOADPATH, fileName + type);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}


/**
* 获取图片链接的后缀名.
* @param fileUrl 图片链接
* @return 图片后缀名  (".gif", ".jpg", ".jpeg",".bmp", ".png")
*/
private static String contain(String fileUrl) {
String[] strings = new String[] { ".gif", ".jpg", ".jpeg", ".bmp", ".png" };
for (int i = 0; i < strings.length; i++) {
String s = strings[i];
if (fileUrl.contains(s))
return s;
}
return ".jpg";
}


/**
* 下载网络图片.
* @param fileUrl 图片地址
*/
public static void downloadCache(final String fileUrl) {
new Thread() {
@Override
public void run() {
Bitmap b = returnBitMap(fileUrl);
try {
saveBitmap(b, BASEPICPATH, fileUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}


/**
* 将网络图片转换为bitmap对象.
* @param url  图片地址
* @return Bitmap
*/
public static Bitmap returnBitMap(String url) {
if (null == url || "".equals(url)) {
return null;
} else {
URL myFileUrl = null;
Bitmap bitmap = null;
try {
myFileUrl = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(3000);
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inSampleSize = 2; //width,hight设为原来的十分一
bitmap = BitmapFactory.decodeStream(is, null, options);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
}


/**
* 保存bitmap对象为图片文件.
* @param bm Bitmap
* @param root 保存路径
* @param fileUrl    文件名
* @throws IOException  IOException
*/
public static void saveBitmap(final Bitmap bm, final String root, final String fileUrl) {
new Thread() {
@Override
public void run() {
LogUtils.e("path:========"+root + filterPath(fileUrl));
File myCaptureFile = new File(root + filterPath(fileUrl));
BufferedOutputStream bos;
try {
bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
bos.flush();
bos.close();
// if(!bm.isRecycled()){
// bm.recycle();   //回收图片所占的内存
//         System.gc();  //提醒系统及时回收
//      } 
super.run();
LogUtils.e("saveBitmap ok  " + root + fileUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}


/**
* 将网络图片转换为.
* @param fileUrl InputStream
* @return InputStream
*/
public static InputStream getInputStreamByImage(String fileUrl) {
try {
Bitmap bitmap = returnBitMap(fileUrl);
if (bitmap != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
InputStream sbs = new ByteArrayInputStream(baos.toByteArray());
return sbs;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}


/**
* 过滤网络连接的特殊字符.
* @param x  网络链接
* @return 过滤后的连接
*/
private static String filterPath(String x) {
return x.replace("\\", "/").replace("?", "").replace("/", "").replace(":", "");
}


/** 
* 获取图片名称获取图片的资源id的方法 .
* @param context Context
* @param imageName 图片名称 
* @return  资源id
*/
public static int getResource(Context context, String imageName) {
int resId = context.getResources().getIdentifier(imageName, "drawable", context.getPackageName());
return resId;
}


/**
* 获取圆角图片.
* @param bitmap Bitmap
* @param bool 是否需要倒影
* @return Bitmap
*/
public static Bitmap GetRoundedCornerBitmap(Bitmap bitmap, boolean bool) {
try {
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);
final float roundPx = 20;


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);


if (bool) {
return createReflectionImageWithOrigin(output);
} else {
return output;
}
} catch (Exception e) {
return bitmap;
}
}


/**
* 获得带倒影的图片方法  
* @param bitmap Bitmap
* @return Bitmap
*/
public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {
// 图片与倒影间隔距离    
final int reflectionGap = 0;
// 图片的宽度    
int width = bitmap.getWidth();
// 图片的高度    
int height = bitmap.getHeight();


Matrix matrix = new Matrix();
// 图片缩放,x轴变为原来的1倍,y轴为-1倍,实现图片的反转  
matrix.preScale(1, -1);
// 创建反转后的图片Bitmap对象,图片高是原图的一半。    
Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height / 2, width, height / 2, matrix, false);
// 创建标准的Bitmap对象,宽和原图一致,高是原图的1.5倍。 可以理解为这张图将会在屏幕上显示 是原图和倒影的合体    
Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height / 2), Config.ARGB_8888);
// 构造函数传入Bitmap对象,为了在图片上画图    
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;
}


/**
* 获取图片.
* 从本地sdcard取图片,本地没有图片的话
* 从网络上把图片取下来,保存在sdcard上
* @param fileUrl 图片网络地址
* @return 文件本地路径 如(file:///sdcard/mobileschool/cache/xxxxxxx.jpg)
*/
public static String getImageSdcardPath(Context context, String fileUrl) {
// return "file:///" + ImageUtil.getImagePath(fileUrl);


try {
String filePath = BASEPICPATH + filterPath(fileUrl);
// 从本地sdcard取图片
if (new File(filePath).exists()) {
return "file:///" + filePath;
} else {
// 从网络上把图片取下来,保存在sdcard上,在保存在map里
// HttpClientUtil.downloadThread(context, fileUrl);
return fileUrl;
}
} catch (Exception e) {
return fileUrl;
}


}


public static Bitmap parseHeadBitmapToLittle(String path){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(path, options);


int mWidth = 120;

int max = options.outWidth>options.outHeight?options.outWidth:options.outHeight;
if(max>mWidth){
options.inSampleSize = max/mWidth;
options.outWidth = 120;
options.outHeight = 120; 

}else{
options.inSampleSize = max/mWidth;
options.outWidth = 120;
options.outHeight = 120;
}
options.inJustDecodeBounds = false;
return getBitmapByPath(path,options);
}


/**
* ��ȡbitmap
* @param filePath
* @return
*/
public static Bitmap getBitmapByPath(String filePath) {
return getBitmapByPath(filePath, null);
}
public static Bitmap getBitmapByPath(String filePath, BitmapFactory.Options opts) {
FileInputStream fis = null;
Bitmap bitmap =null; 
try { 
File file = new File(filePath);
fis = new FileInputStream(file);
bitmap = BitmapFactory.decodeStream(fis,null,opts);
} catch (FileNotFoundException e) {  
e.printStackTrace();
} catch (OutOfMemoryError e) {
e.printStackTrace();
} finally{
try {
fis.close();
} catch (Exception e) {}
}
return bitmap;
}
/**
     * @Title: getUriString
     * @param uri
     * @return
     * @return String
     * @date 2012-11-28 ����1:19:31
     */
    public static String getUriString(Uri uri,ContentResolver cr){
    String imgPath = null;
    if (uri != null) {
    String uriString = uri.toString();
    if(uriString.startsWith("file")){ 
    imgPath = uriString.substring(7, uriString.length());
    return imgPath;
    }
    Cursor cursor = cr.query(uri, null, null,null, null);
    cursor.moveToFirst();
    imgPath = cursor.getString(1);
   
    }
    return imgPath;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值