android 拍照或者图库选择 压缩后 图片 上传
通过拍照或者从相册里选择图片通过压缩并上传时很多应用的常用功能,记录一下实现过程
一:创建个临时文件夹用于保存压缩后需要上传的图片
/**
* path:存放图片目录路径
*/
private String path = Environment.getExternalStorageDirectory().getPath() + "/XXX/";
/**
* saveCatalog:保存文件目录
*/
private File saveCatalog; /**
* saveFile:保存的文件
*/
private File saveFile; public String createOrGetFilePath(String fileName, Context mContext) {
saveCatalog = new File(path);
if (!saveCatalog.exists()) {
saveCatalog.mkdirs();
}
saveFile = new File(saveCatalog, fileName);
try {
saveFile.createNewFile();
} catch (IOException e) {
Toast.makeText(mContext, "创建文件失败,请检查SD是否有足够空间", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
return saveFile.getAbsolutePath();
}
二:通过对话框选择获得图片方式(拍照或者相册) <string-array name="get_image_way">
<item >拍照</item>
<item >相册</item>
</string-array>
private String[] image;
image = getResources().getStringArray(R.array.get_image_way); /**
* TODO 通过拍照或者图册获得照片
*
* @author {author wangxiaohong}
*/
private void selectImage() {
// TODO Auto-generated method stub
String state = Environment.getExternalStorageState();
if (!state.equals(Environment.MEDIA_MOUNTED)) {
Util.showToast(this, getResources().getString(R.string.check_sd)); //检查SD卡是否可用
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.pick_image).setItems(image,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (image[which].equals(getString(R.string.my_data_image_way_photo))) {
getImageByPhoto();
} else {
getImageByGallery();
}
}
});
builder.create().show();
} private void getImageByGallery() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent, IMAGE_RESULT);
}
public String getPath(String carId, String fileName, Context mContext) {
File saveCatalog = new File(Constant.CACHE, carId);
// saveCatalog = new File(path);
if (!saveCatalog.exists()) {
saveCatalog.mkdirs();
}
saveFile = new File(saveCatalog, fileName);
try {
saveFile.createNewFile();
} catch (IOException e) {
Toast.makeText(mContext, "创建文件失败,请检查SD是否有足够空间", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
return saveFile.getAbsolutePath();
}
private void getImageByPhoto() {
public static final String CACHE = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/pinchebang/";
path = util.getPath(user.getCar().getCarId() + "", mPhotoName, PersonalInfoActivity.this);
imageUri = Uri.fromFile(new File(path));
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, CAMERA_RESULT);
}
三:在onActivityResult中得到的图片做压缩处理
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) return;
Bitmap bitmap = null;
if (requestCode == CAMERA_RESULT) {
bitmap = util.getSmallBitmap(PersonalInfoActivity.this, path);
boolean flag = util.save(PersonalInfoActivity.this, path, bitmap);
} else if (requestCode == IMAGE_RESULT) {
Uri selectedImage = data.getData();
path = util.getImagePath(PersonalInfoActivity.this, selectedImage);
bitmap = util.getSmallBitmap(PersonalInfoActivity.this, path);
String pcbPathString = util.getPath(user.getCar().getCarId() + "", mPhotoName,
PersonalInfoActivity.this);
;
util.save(PersonalInfoActivity.this, pcbPathString, bitmap);
path = pcbPathString;
}
if (null != bitmap) {
mypicture.setImageBitmap(bitmap);
HttpUtil.uploadFile(PersonalInfoActivity.this, path, "userImg",
Constant.URL_VERIFY_DRIVER);
// MemoryCache memoryCache = new MemoryCache();
// memoryCache.put(url, bitmap);
}
}
上面对应的压缩方法 /**
* TODO filePath:图片路径
*
* @author {author wangxiaohong}
*/
public Bitmap getSmallBitmap(Context mContext, String filePath) {
DisplayMetrics dm;
dm = new DisplayMetrics();
((Activity) mContext).getWindowManager().getDefaultDisplay().getMetrics(dm);
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, dm.widthPixels, dm.heightPixels);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filePath, options);
} public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) { // Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth); // Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
} /**
* TODO 保存并压缩图片 将bitmap 保存 到 path 路径的文件里
*
* @author {author wangxiaohong}
*/
public boolean save(Context mContext, String path, Bitmap bitmap) {
DisplayMetrics dm;
dm = new DisplayMetrics();
((Activity) mContext).getWindowManager().getDefaultDisplay().getMetrics(dm);
if (path != null) {
try {
// FileCache fileCache = new FileCache(mContext);
// File f = fileCache.getFile(url);
File f = new File(path);
FileOutputStream fos = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fos);
saveMyBitmap(bitmap);
return true;
} catch (Exception e) {
return false;
}
} else {
return false;
}
} private void saveMyBitmap(Bitmap bm) {
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(saveFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bm.compress(Bitmap.CompressFormat.JPEG, 70, fOut);
try {
fOut.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
} public String getPath(String carId, String fileName, Context mContext) {
File saveCatalog = new File(Constant.CACHE, carId);
// saveCatalog = new File(path);
if (!saveCatalog.exists()) {
saveCatalog.mkdirs();
}
saveFile = new File(saveCatalog, fileName);
try {
saveFile.createNewFile();
} catch (IOException e) {
Toast.makeText(mContext, "创建文件失败,请检查SD是否有足够空间", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
return saveFile.getAbsolutePath(); } /**
* TODO 获得相册选择图片的图片路径
*
* @author {author wangxiaohong}
*/
public String getImagePath(Context mContext, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = mContext.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String ImagePath = cursor.getString(column_index);
cursor.close();
return ImagePath;
}
四:上传
public static void uploadFile(Context mContext, String path, String modelValue, String url) {
new PhotoUploadAsyncTask(mContext).execute(path, modelValue, url);
}
class PhotoUploadAsyncTask extends AsyncTask<String, Integer, String> {
// private String url = "http://192.168.83.213/receive_file.php";
private Context context;
public PhotoUploadAsyncTask(Context context) {
this.context = context;
}
@Override
protected void onPreExecute() {
}
@SuppressWarnings("deprecation")
@Override
protected String doInBackground(String... params) {
// 保存需上传文件信息
MultipartEntityBuilder entitys = MultipartEntityBuilder.create();
entitys.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entitys.setCharset(Charset.forName(HTTP.UTF_8));
File file = new File(params[0]);
entitys.addPart("image", new FileBody(file));
entitys.addTextBody("model", params[1]);
HttpEntity httpEntity = entitys.build();
return HttpUtil.uploadFileWithpost(params[2], context, httpEntity);
}
@Override
protected void onProgressUpdate(Integer... progress) {
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(context, result, Toast.LENGTH_SHORT).show();
}
}
/**
* 用于文件上传
*
* @param url
* @param mContext
* @param entity
* @return
*/
@SuppressWarnings("deprecation")
public static String uploadFileWithpost(String url, Context mContext, HttpEntity entity) {
Util.printLog("开始上传");
try {
setTimeout();
httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
// 设置连接超时时间
// httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
// 5000);
HttpPost upPost = new HttpPost(url);
upPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(upPost, httpContext);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return mContext.getString(R.string.upload_success);
}
} catch (Exception e) {
Util.printLog("上传报错");
e.printStackTrace();
}
// finally {
// if (httpClient != null && httpClient.getConnectionManager() != null)
// {
// httpClient.getConnectionManager().shutdown();
// }
// }
Util.printLog("上传成功");
return mContext.getString(R.string.upload_fail);
}
android 拍照或者图库选择 压缩后 图片 上传的更多相关文章
- Android拍照得到全尺寸图片并进行压缩/拍照或者图库选择 压缩后 图片 上传
http://www.jb51.net/article/77223.htm https://www.cnblogs.com/breeze1988/p/4019510.html
- ueditor 编辑器上传到服务器后图片上传不能正常使用
网站集成ueditor编辑器后在本地能正常使用,上传到服务器上后,图片上传功能提示:后端配置项没有正常加载,上传插件不能正常使用.且单个图片上传图标是灰色的不能点击. 相信遇到这个问题的同学是很多的吧 ...
- android拍照选择图片上传服务器自定义控件
做android项目的时候总免不了遇到图片上传功能,虽然就是调用android系统的拍照和相册选择功能,但是总面部了把一大推代码写在activity里,看上去一大推代码头都昏了.不如把这些功能都集成一 ...
- html5图片上传时IOS和Android均显示摄像头拍照和图片选择
最近在做信开发时,发现<input type="file" />在IOS中可以拍照或从照片图库选择,而Android系统则显示资源管理器,无拍照选项,网上查找资料,改为 ...
- Android 从 Android 本地图库选择多个图片
原文地址 本文说明如何从 Android 本地图库选择多个图片.作者考虑很多解决方案. 演示从 Android 本地图库选择多个图片,有两个方法可以实现从图库中选择多个图片: 用 Intent 获取多 ...
- html + js 实现图片上传,压缩,预览及图片压缩后得到Blob对象继续上传问题
先上效果 上传图片后(设置了最多上传3张图片,三张后上传按钮消失) 点击图片放大,可以使用删除和旋转按钮 (旋转功能主要是因为ios手机拍照后上传会有写图片被自动旋转,通过旋转功能可以调正) html ...
- 图片上传前 压缩,base64图片压缩 Exif.js处理ios拍照倒置等问题
曾写过在前端把图片按比例压缩不失真上传服务器的前端和后台,可惜没有及时做总结保留代码,只记得js利用了base64位压缩和Exif.js进行图片处理,还有其中让我头疼的ios拍照上传后会倒置等诸多问题 ...
- HTML5 Plus 拍照或者相册选择图片上传
HBuilder+HTML5 Plus+MUI实现拍照或者相册选择图片上传,利用HTML5 Plus的Camera.Gallery.IO.Storage和Uploader来实现手机APP拍照或者从相册 ...
- Android仿微信图片上传,可以选择多张图片,缩放预览,拍照上传等
仿照微信,朋友圈分享图片功能 .可以进行图片的多张选择,拍照添加图片,以及进行图片的预览,预览时可以进行缩放,并且可以删除选中状态的图片 .很不错的源码,大家有需要可以下载看看 . 微信 微信 微信 ...
随机推荐
- 值得珍藏的.NET源码,不保存就没机会了
很早以前,我们通过http://referencesource.microsoft.com/netframework.aspx可以下载到.NET的各版本公开源码,但如今,微软对sscli项目进行了改版 ...
- YUV到RGB的转换
以下内容来源于网络,下面三个链接里的内容是比较好的,感谢博主的分享. http://blog.csdn.net/housisong/article/details/1859084 http://blo ...
- 20-语言入门-20-Financial Management
题目地址: http://acm.nyist.edu.cn/JudgeOnline/problem.php?pid=72 描述Larry graduated this year and fina ...
- 04-语言入门-04-Fibonacci数
地址: http://acm.nyist.net/JudgeOnline/problem.php?pid=13 描述 无穷数列1,1,2,3,5,8,13,21,34,55...称为Fibona ...
- poj 2115 C Looooops(扩展gcd)
题目链接 这个题犯了两个小错误,感觉没错,结果怒交了20+遍,各种改看别人题解,感觉思路没有错误,就是wa. 后来看diccuss和自己查错,发现自己的ecgcd里的x*(a/b)写成了x*a/b.还 ...
- voliecty indexOf的写法
Velocity allows you to use all Java methods available in your objects. So just write as if it was Ja ...
- Oracle的rownum原理和使用(整理几个达人的帖子)
整理和学习了一下网上高手关于rownum的帖子: 参考资料: http://tech.ddvip.com/2008-10/122490439383296.html 和 http://tenn.jav ...
- bzoj3926
题目的意思是叶子不超过20个……听说当初zjoi不少人被坑 分别对每个叶子以它为根dfs出20个dfs树,这样整个树的任何一个子串,都是某个dfs树上一个点到它的一个子孙的路径 每个dfs树,根到叶子 ...
- bzoj1997: [Hnoi2010]Planar
2-SAT. 首先有平面图定理 m<=3*n-6,如果不满足这条件肯定不是平面图,直接退出. 然后构成哈密顿回路的边直接忽略. 把哈密顿回路当成一个圆, 如果俩条边交叉(用心去感受),只能一条边 ...
- Windows SDK 实现不规则窗口介绍
不规则窗口在程序界面设计中能提供非常好的用户体验,以下是我程序运行时的效果图: 以下是代码,注意需要修改一些简单的位置,如资源ID,项目的头文件等,这些是根据你创建的win32程序的项目名改变的,我的 ...