從相冊獲取圖片及調用相機拍照獲取圖片,最後上傳圖片到服務器,相機上傳圖片
調用相機拍照獲取圖片:
跳轉到到拍照界面:
Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//下面這句指定調用相機拍照後的照片存儲的路徑
mSzImageFileName = Long.toString(System.currentTimeMillis()) + ".png";
takeIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(new File(Environment.getExternalStorageDirectory(), mSzImageFileName)));
startActivityForResult(takeIntent, REQUEST_TAKE_PHOTO);
從相冊獲取圖片:
從相冊選擇圖片:
Intent pickIntent = new Intent(Intent.ACTION_PICK, null);
// 如果要限制上傳到服務器的圖片類型時可以直接寫如:image/jpeg 、 image/png等的類型
pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(pickIntent, REQUEST_PICK_PHOTO);
從相冊返回一張圖片或者拍照返回一張圖片:
監聽返回結果:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_PICK_PHOTO:// 直接從相冊獲取
try {
startPhotoZoom(data.getData());//跳轉到截圖界面
} catch (NullPointerException e) {
e.printStackTrace();// 用戶點擊取消操作
}
break;
case REQUEST_TAKE_PHOTO:// 調用相機拍照
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
File temp = new File(Environment.getExternalStorageDirectory(), mSzImageFileName);
if (temp.exists()) {
startPhotoZoom(Uri.fromFile(temp));//跳轉到截圖界面
}
}
}, 1000);
break;
case REQUEST_CUT_PHOTO:// 取得裁剪後的圖片
if (data != null) {
setPicToView(data);//保存和上傳圖片
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
返回圖片後進行裁剪:
裁剪圖片:
/**
* 裁剪圖片方法實現
*/
private void startPhotoZoom(Uri uri) {
LogUtil.e("PersonalInformationActivity", "onActivityResult uri" + uri);
if (uri != null) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
// 下面這個crop=true是設置在開啟的Intent中設置顯示的VIEW可裁剪
intent.putExtra("crop", "true");
// aspectX aspectY 是寬高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX outputY 是裁剪圖片寬高
intent.putExtra("outputX", 300);
intent.putExtra("outputY", 300);
intent.putExtra("return-data", true);
startActivityForResult(intent, REQUEST_CUT_PHOTO);
}
}
裁剪後保存和上傳圖片:
/**
* 保存裁剪之後的圖片數據
*
* @param picdata
*/
private void setPicToView(Intent picdata) {
Bundle extras = picdata.getExtras();
if (extras != null) {
// 取得SDCard圖片路徑做顯示
Bitmap photo = extras.getParcelable("data");
mSzImageFileName = Long.toString(System.currentTimeMillis()) + ".png";
mImgUrlPath = Environment.getExternalStorageDirectory() + File.separator + "cut_image" + File.separator + mSzImageFileName;
try {
NetUtil.saveBitmapToFile(photo, mImgUrlPath);
} catch (IOException e) {
e.printStackTrace();
}
// 新線程後台上傳服務端
new Thread(uploadImageRunnable).start();
}
}
上傳圖片的線程:
Runnable uploadImageRunnable = new Runnable() {
@Override
public void run() {
Map<String, String> params = new HashMap<>();
params.put("mid", mSzId);//上傳參數
Map<String, File> files = new HashMap<>();
files.put("myUpload", new File(mImgUrlPath));//上傳文件路徑
try {
String json = NetUtil.uploadFile(Constants.URL_EDIT_IMG, params, files);
//json為服務器返回的數據,可自己解析(如json解析)取得想要的數據
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
保存圖片和上傳圖片的工具類NetUtil :
public class NetUtil {
//上傳圖片到服務器
public static String uploadFile(String url, Map<String, String> params, Map<String, File> files)
throws IOException {
String tempStr = null;
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--", LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
HttpURLConnection conn = null;
try {
URL uri = new URL(url);
conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(10 * 1000); // 緩存的最長時間
conn.setDoInput(true);// 允許輸入
conn.setDoOutput(true);// 允許輸出
conn.setUseCaches(false); // 不允許使用緩存
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
// 首先組拼文本類型的參數
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}
LogUtil.e("NetUtil", "uploadFile sb:" + sb.toString());
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(sb.toString().getBytes());
// 發送文件數據
if (files != null)
for (Map.Entry<String, File> file : files.entrySet()) {
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition: form-data; name="+file.getKey()
+"; filename=\""
+ file.getValue() + "\"" + LINEND);
sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
sb1.append(LINEND);
LogUtil.e("NetUtil", "uploadFile sb1:" + sb1.toString());
outStream.write(sb1.toString().getBytes());
InputStream is = new FileInputStream(file.getValue());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
outStream.write(LINEND.getBytes());
}
// 請求結束標志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
outStream.close();
StringBuilder sb2 = new StringBuilder();
BufferedReader in = new BufferedReader(new InputStreamReader(conn
.getInputStream(), CHARSET));
String inputLine;
while ((inputLine = in.readLine()) != null) {
sb2.append(inputLine);
}
in.close();
tempStr = sb2.toString();
} catch (Exception e) {
} finally {
if (conn != null) {
conn.disconnect();
}
}
return tempStr;
}
/**
* Save Bitmap to a file.保存圖片到SD卡。
*
* @param bitmap
* @return error message if the saving is failed. null if the saving is
* successful.
* @throws IOException
*/
public static void saveBitmapToFile(Bitmap bitmap, String _file)
throws IOException {
BufferedOutputStream os = null;
try {
File file = new File(_file);
int end = _file.lastIndexOf(File.separator);
String _filePath = _file.substring(0, end);
File filePath = new File(_filePath);
if (!filePath.exists()) {
filePath.mkdirs();
}
file.createNewFile();
os = new BufferedOutputStream(new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
}
}
}