Android撮影またはライブラリ選択圧縮後の画像アップロード
10838 ワード
写真を撮ったり、アルバムから画像を選んだりして圧縮してアップロードするときの多くのアプリケーションの常用機能を通じて、実現過程を記録します.
一:圧縮後にアップロードする画像を保存するための一時フォルダを作成する
二:ダイアログで選択して画像を得る方法(写真やアルバム)
三:onActivity Resultで得られた画像を圧縮処理する
四:アップロード
一:圧縮後にアップロードする画像を保存するための一時フォルダを作成する
/**
* 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();
}
二:ダイアログで選択して画像を得る方法(写真やアルバム)
<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);
}
三:onActivity Resultで得られた画像を圧縮処理する
@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);
}