首先启动相机调用改方法
/** * 启动拍照 */ public void startCamera() { try { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //将图片保存至SDcard,相机返回后直接在SDcard读取图片,这样可以解决获取的图片太小的问题。 intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(getPhotopath()))); startActivityForResult(intent, 7); } catch (Exception e) { // TODO: handle exception } }
/** * 获取原图片存储路径 * @return */ public String getPhotopath() { // 照片全路径 String fileName = ""; // 文件夹路径 String pathUrl = Environment.getExternalStorageDirectory()+"/test/"; String imageName = "camera.png"; File file = new File(pathUrl); file.mkdirs();// 创建文件夹 fileName = pathUrl + imageName; return fileName; }
if (requestCode == 7) { bitmap=getBitmap(); if(bitmap==null){//提示语句}else {//得到bitmap数据压缩后上传就OK了
}}savebitmap()
public Bitmap getBitmap() { Bitmap bitmap = null; try { FileInputStream fis = new FileInputStream(getPhotopath()); bitmap = BitmapFactory.decodeStream(fis); } catch (FileNotFoundException e) { e.printStackTrace(); } return bitmap; }
本地图片压缩改一下就可以上传服务器了的
//本地图片压缩 private void savebitmap(){ //先将所选图片转化为流的形式,path所得到的图片路径 try { FileInputStream is = new FileInputStream(getPhotopath()); //定义一个file,为压缩后的图片 File f = new File(Environment.getExternalStorageDirectory()+"/test/","testcamera.png"); int size = 4; BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = size; //将图片缩小为原来的 1/size ,不然图片很大时会报内存溢出错误 Bitmap image = BitmapFactory.decodeStream(is,null,options); is.close(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//这里100表示不压缩,将不压缩的数据存放到baos中 int per = 100; while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于500kb,大于继续压缩 baos.reset();// 重置baos即清空baos image.compress(Bitmap.CompressFormat.JPEG, per, baos);// 将图片压缩为原来的(100-per)%,把压缩后的数据存放到baos中 per -= 10;// 每次都减少10 } //String resultData=new String(baos.toByteArray()); 若上传服务器,转换成字符串 //回收图片,清理内存 if(image != null && !image.isRecycled()){ image.recycle(); image = null; System.gc(); } ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中 FileOutputStream os; os = new FileOutputStream(f); //将输入流复制到输出流中 byte[] b = new byte[1024]; int len; while ((len=isBm.read(b))!=-1){ os.write(b,0,len); } } catch (Exception e) { } }
OK大致就这样吧