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仿微信图片上传,可以选择多张图片,缩放预览,拍照上传等
仿照微信,朋友圈分享图片功能 .可以进行图片的多张选择,拍照添加图片,以及进行图片的预览,预览时可以进行缩放,并且可以删除选中状态的图片 .很不错的源码,大家有需要可以下载看看 . 微信 微信 微信 ...
随机推荐
- linux 免交互状态下修改用户密码
当利用某些工具对linux用户进行远程密码更改时,输入[ passwd 用户名 ] 后需要输入两次密码, 但是如果你利用的某些工具无法与linux进行交互的情况下,就没办法变更用户密码了,这个时候可以 ...
- Linux 查看版本详情
内核版本的信 uname -a -a选项表示察看所有的信息,但是从输出信息可以看出来,uname看到的版本信息,只是内核版本的信息,而不是发行版的版本信息 查看发行版信息 $cat /etc/issu ...
- (四)CSS选择器和派生选择器
CSS派生选择器允许你根据文档的上下文关系来确定某个标签的样式.在学习派生之前,先来了解基本的CSS选择器.前面的文章中提到过下图,选择器的位置如下所示: CSS选择器 分为几种基本选择器:元素选择器 ...
- ZOJ 3607 Lazier Salesgirl(贪心)
题目:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3607 题意:一个卖面包的小姑娘,给第i个来买面包的人的价格是pi, ...
- LA 5846 (计数) Neon Sign
从反面考虑,统计非单色三角形的个数. 如果从一个点出发两条不同颜色的边,那么这三个点一定构成一个非单色三角形. 枚举一个顶点,统计从这个点出发的红边的个数a[i]和蓝边的个数n - 1 - a[i], ...
- [反汇编练习] 160个CrackMe之018
[反汇编练习] 160个CrackMe之018. 本系列文章的目的是从一个没有任何经验的新手的角度(其实就是我自己),一步步尝试将160个CrackMe全部破解,如果可以,通过任何方式写出一个类似于注 ...
- NSIS 2.0界面快速入门
NSIS 2.0 版本支持定制的用户界面.所谓的 Modern UI(下称 MUI) 就是一种模仿最新的 Windows 界面风格的界面系统.MUI 改变了 NSIS 脚本的编写习惯,它使用 NSIS ...
- OK335xS psplash 进度条工作原理 hacking
#!/bin/sh # # rc This file is responsible for starting/stopping # services when the runlevel changes ...
- erl0003-ets 几种类型的区别和ets效率建议 <转>
rlang内置大数据量数据库 ets,dets 初窥 发布日期:2011-10-24 18:45:48 作者:dp studio ets是Erlang term storage的缩写, dets则 ...
- linux编程获取本机网络相关参数
getifaddrs()和struct ifaddrs的使用,获取本机IP 博客分类: Linux C编程 ifaddrs结构体定义如下: struct ifaddrs { struct ifad ...