选取照片方法: 打开系统相册
首先看Activity中的点击事件:
case R.id.img_addPicture:
// 打开系统相册
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");// 相片类型
startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE1);
break;
接下来看里面的onActivityResult()方法:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK) {
return;
}
if (requestCode == REQUEST_CODE_PICK_IMAGE) {
Uri uri = data.getData();
startPhotoZoom(data.getData());
}
else if(requestCode == REQUEST_CODE_PICK_IMAGE1){
Uri uri = data.getData();
richText.insertImage(mFileUtils.getFilePathFromUri(uri));
//startPhotoZoom1(data.getData());
}
else if (requestCode == REQUEST_CODE_CAPTURE_CAMEIA
&& resultCode == Activity.RESULT_OK) {
richText.insertImage(mCameraImageFile.getAbsolutePath());
}else if(requestCode==CROP_SMALL_PICTURE){
if (data != null) {
Bitmap bitmap = data.getExtras().getParcelable("data");
ft.setImageBitmap(bitmap);
setImageToView(data); // 让刚才选择裁剪得到的图片显示在界面上
}
}
}
这里包含了几个处理,先看requestCode == REQUEST_CODE_PICK_IMAGE
的时候,先获取了具体的uri,然后调用startPhotoZoom()进行裁剪后上传。
protected void startPhotoZoom(Uri uri) {
if (uri == null) {
Log.i("tag", "The uri is not exist.");
}
tempUri = uri;
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
// 设置裁剪
intent.putExtra("crop", "true");
// aspectX aspectY 是宽高的比例
intent.putExtra("aspectX", 0.1);
intent.putExtra("aspectY", 0.1);
// outputX outputY 是裁剪图片宽高
intent.putExtra("outputX", 150);
intent.putExtra("outputY", 150);
intent.putExtra("return-data", true);
intent.putExtra("scale", true);
startActivityForResult(intent, CROP_SMALL_PICTURE);
}
然后再返回到startActivityForResult()方法中卡看
else if(requestCode==CROP_SMALL_PICTURE){
if (data != null) {
Bitmap bitmap = data.getExtras().getParcelable("data");
ft.setImageBitmap(bitmap);
setImageToView(data); // 让刚才选择裁剪得到的图片显示在界面上
}
}
先让图片转化成Bitmap类型的,再进行下一步的处理
protected void setImageToView(Intent data) {
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
uploadPic(photo);
}
}
真正上传的方法在这里:
rivate void uploadPic(Bitmap bitmap) {
// 上传至服务器
// ... 可以在这里把Bitmap转换成file,然后得到file的url,做文件上传操作
// 注意这里得到的图片已经是圆形图片了
// bitmap是没有做个圆形处理的,但已经被裁剪了
Time time = new Time();
time.setToNow();
Imageid = String.valueOf(time.year)
+ String.valueOf(time.month + 1) + String.valueOf
(time.monthDay) +String.valueOf(time.hour)+String.valueOf(time.minute)+ String.valueOf(time.second) + "";
String imagePath = Utils.savePhoto(bitmap, Environment
.getExternalStorageDirectory().getAbsolutePath()
+ "/TravelPersonal_icon", Imageid);
File file =new File(imagePath);
Log.d("imagePath", imagePath + "");
if (imagePath != null) {
// 拿着imagePath上传了
new Thread(new UpFile()).start();
}
}
启动的另一个线程的方法:
private class UpFile implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
String filePath = "/storage/emulated/0/TravelPersonal_icon/";
filePath =filePath+Imageid+".png";
Log.e("上传文件路径....", filePath+"");
ArrayList<String> array = new ArrayList<String>();
array.add(filePath);
InfoService.upload(Tools.url_uploadMyImage, array, NoteActivity.this.getBaseContext());
String str = "images/"+Imageid+".png";
us.setImage(str);
}
}
先说说这两个方法的逻辑,其实就是先给选取好的图片进行自定义的命名根据它的路径,如果图片不为空就启动新线程进行上传。在上传方法中,我把文件路径保存在了一个ArrayList的数组当中,最后就是启动方法InfoService.upload(Tools.url_uploadMyImage, array, NoteActivity.this.getBaseContext());
进行上传,第一个参数是服务器上传图片的url,第二个是上传的文件路径,第三个是context。
下面就是InfoService.upload()的具体内容:
public static String upload(String post_url, ArrayList<String> files, Context context) {
StringBuffer stringBuffer = new StringBuffer();
Log.e("file upload..url is ",post_url+"====");
try {
String BOUNDARY = "---------7d4a6d158c9"; // 定义数据分隔线
URL url = new URL(post_url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
//连接服务器后是否关闭连接(常连接)
//conn.setRequestProperty("connection", "Keep-Alive");
//浏览器类型
//conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
//conn.setRequestProperty("richmj_token", DateUtil.getToken(context));
OutputStream out = new DataOutputStream(conn.getOutputStream());
byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线
int leng = files.size();
int j = 1;
for (int i = 0; i < leng; i++) {
String fname = files.get(i);
File file = new File(fname);
StringBuilder sb = new StringBuilder();
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"picfile" + j + "\";filename=\"" + file.getName() + "\"\r\n");
j++;
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] data = sb.toString().getBytes();
out.write(data);
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
out.write("\r\n".getBytes()); //多个文件时,二个文件之间加入这个
in.close();
}
out.write(end_data);
out.flush();
out.close();
Log.e("上传文件返回===》","上传文件返回信息");
// 定义BufferedReader输入流来读取URL的响应
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
stringBuffer.append(line);
}
} catch (Exception e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
}
return stringBuffer.toString();
}
首先,定义了一个分割线,然后获取了具体的url。接下来就是使用HttpUrlConnection进行网络连接,还有定义完所需要的一些东西,最后在循环语句中使用StringBuilder类来进行所有信息的拼凑,然后装进byte型的数组当中,使用outPutStream.write()写入,记得把相应的输入输出流关闭。
还有,定义BufferedReader输入流来读取URL的响应判断文件返回信息是否有异常,有异常则要进行抛出。
结束
对于图片上传自用感觉可以,逻辑方面的处理还有很多理解不到位的,希望大佬指教一下