通过拍照或者从相册里选择图片通过压缩并上传时很多应用的常用功能,记录一下实现过程

一:创建个临时文件夹用于保存压缩后需要上传的图片

        /**
* 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 拍照或者图库选择 压缩后 图片 上传的更多相关文章

  1. Android拍照得到全尺寸图片并进行压缩/拍照或者图库选择 压缩后 图片 上传

    http://www.jb51.net/article/77223.htm https://www.cnblogs.com/breeze1988/p/4019510.html

  2. ueditor 编辑器上传到服务器后图片上传不能正常使用

    网站集成ueditor编辑器后在本地能正常使用,上传到服务器上后,图片上传功能提示:后端配置项没有正常加载,上传插件不能正常使用.且单个图片上传图标是灰色的不能点击. 相信遇到这个问题的同学是很多的吧 ...

  3. android拍照选择图片上传服务器自定义控件

    做android项目的时候总免不了遇到图片上传功能,虽然就是调用android系统的拍照和相册选择功能,但是总面部了把一大推代码写在activity里,看上去一大推代码头都昏了.不如把这些功能都集成一 ...

  4. html5图片上传时IOS和Android均显示摄像头拍照和图片选择

    最近在做信开发时,发现<input type="file" />在IOS中可以拍照或从照片图库选择,而Android系统则显示资源管理器,无拍照选项,网上查找资料,改为 ...

  5. Android 从 Android 本地图库选择多个图片

    原文地址 本文说明如何从 Android 本地图库选择多个图片.作者考虑很多解决方案. 演示从 Android 本地图库选择多个图片,有两个方法可以实现从图库中选择多个图片: 用 Intent 获取多 ...

  6. html + js 实现图片上传,压缩,预览及图片压缩后得到Blob对象继续上传问题

    先上效果 上传图片后(设置了最多上传3张图片,三张后上传按钮消失) 点击图片放大,可以使用删除和旋转按钮 (旋转功能主要是因为ios手机拍照后上传会有写图片被自动旋转,通过旋转功能可以调正) html ...

  7. 图片上传前 压缩,base64图片压缩 Exif.js处理ios拍照倒置等问题

    曾写过在前端把图片按比例压缩不失真上传服务器的前端和后台,可惜没有及时做总结保留代码,只记得js利用了base64位压缩和Exif.js进行图片处理,还有其中让我头疼的ios拍照上传后会倒置等诸多问题 ...

  8. HTML5 Plus 拍照或者相册选择图片上传

    HBuilder+HTML5 Plus+MUI实现拍照或者相册选择图片上传,利用HTML5 Plus的Camera.Gallery.IO.Storage和Uploader来实现手机APP拍照或者从相册 ...

  9. Android仿微信图片上传,可以选择多张图片,缩放预览,拍照上传等

    仿照微信,朋友圈分享图片功能 .可以进行图片的多张选择,拍照添加图片,以及进行图片的预览,预览时可以进行缩放,并且可以删除选中状态的图片 .很不错的源码,大家有需要可以下载看看 . 微信 微信 微信 ...

随机推荐

  1. chmod u+x 脚本文件

    [root@ossec-server Shell]# chmod u+x whologged.sh解释: chmod:改变权限 u:文件所有用户 +x: 增加可执行权限 [root@ossec-ser ...

  2. renameTo()方法的用法

    使用renameTo()方法,可以将文件data.txt从C:\JavaApp\IOTest1\目录移动到C:\目录,并改名为newdata.txt import java.io.File; //将文 ...

  3. UPC 2224 / “浪潮杯”山东省第四届ACM大学生程序设计竞赛 1008 Boring Counting 主席树

    Problem H:Boring Counting Time Limit : 6000/3000ms (Java/Other)   Memory Limit : 65535/32768K (Java/ ...

  4. 分享一个免费SSL证书申请网站,给网站开启https协议 | 张戈博客

    这些天,由于公司的业务需求,接触到了ssl证书和https协议.博客前几篇文章也分享了在WEB服务器上安装SSL证书,为网站开启https协议的教程,感兴趣的童鞋可以前往查看相关文章: <Lin ...

  5. linux下拷贝整个目录

    该命令的功能是将给出的文件或目录拷贝到另一文件或目录中,就如同DOS下的copy命令一样,功能非常强大. 语法:cp [选项] 源文件或目录 目标文件或目录 说明:该命令把指定的源文件复制到目标文件或 ...

  6. POJ 1808 Quadratic Residues(平方剩余相关)

    题目链接:http://poj.org/problem?id=1808 题意:如下.对于素数p,若存在x使得x^2%p=a,则其值为1.否则为-1.现在给出a.p,计算其值. 思路: 若a为正数则利用 ...

  7. js中的this怎么理解

    本博客供自己学习备忘, js中的this感觉很混乱,目前还有不少地方搞得不是很清楚,看到一篇不错的文章,先摘下来 this是Javascript语言的一个关键字它代表函数运行时,自动生成的一个内部对象 ...

  8. Android Handler 避免内存泄漏的用法总结

    Android开发经常会用到handler,但是我们发现每次使用Handler都会出现:This Handler class should be static or leaks might occur ...

  9. “main cannot be resolved or is not a field”解决方案

    .layout.main总是在layout上有错误提示波浪线. 解决方法: (1) 删除"import android.R;". (2) 勾选上Eclipse中的"Pro ...

  10. hdu 5310 Souvenir (水)

    题意:今天是BestCoder一周年纪念日. 比赛管理员Soda想要给每个参赛者准备一个纪念品. 商店里纪念品的单价是p元, 同时也可以花q元购买纪念品套装, 一个套装里有m个纪念品.今天总共有n个参 ...