Android 图片压缩上传

结合网上的资源以及项目中的使用整理:

项目中经常有图片上传的功能,解决图片大小是个很重要的问题,以下是网络上的常用方法

String imagePath = "";//图片的地址

public Bitmap getSmallBitmap(String filePath) {


final BitmapFactory.Options options = new BitmapFactory.Options();
//设置成true之后,bitmap可以先不加载到内存而取到我们要用的值
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);

Display display = getWindowManager().getDefaultDisplay();
// options.inSampleSize可以理解为压缩率  当<=1时表示已原来大小加载 >1时如2就是一它原来的1/2长宽加载
options.inSampleSize = calculateInSampleSize(options,
display.getWidth(), display.getHeight());
options.inPreferredConfig = Config.RGB_565;


//  /设置成false之后,就可以得到我们的bitmap
options.inJustDecodeBounds = false;


Bitmap bm = BitmapFactory.decodeFile(filePath, options);
if (bm == null) {
return null;
}
//图片旋转角度设置
int degree = readPictureDegree(filePath);
bm = rotateBitmap(bm, degree);
return bm;


}private int readPictureDegree(String path) {
int degree = 0;
try {
ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
} catch (IOException e) {
e.printStackTrace();
}
return degree;
}


private Bitmap rotateBitmap(Bitmap bitmap, int rotate) {
if (bitmap == null)
return null;


int w = bitmap.getWidth();
int h = bitmap.getHeight();


Matrix mtx = new Matrix();
mtx.postRotate(rotate);
return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
}


private int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? widthRatio : heightRatio;
}
return inSampleSize;
}
 

这样的们的他图片就处理完了,要想上传还要进行压缩处理如下

ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 30, baos);// 压缩图片格式为PNG,质量100%。这里要注意Png是无损压缩,jpg会稍微影响分辨率,30相当于压缩到原来70%。
byte[] body = baos.toByteArray();
String uploadBuffer = new String(Base64.encode(body, Base64.DEFAULT));//将bitmap变成byte[]数组之后同base64编码进行上传


2.在实际项目中 比如说服务器要求上传的时候是表单上传,要下下面的方法:

public class UploadUtil {
private static UploadUtil uploadUtil;
private static final String BOUNDARY = UUID.randomUUID().toString(); // 边界标识
// 随机生成
private static final String PREFIX = "--";
private static final String LINE_END = "\r\n";
private static final String CONTENT_TYPE = "multipart/form-data"; // 内容类型


private UploadUtil() {


}


/**
* 单例模式获取上传工具类

* @return
*/
public static UploadUtil getInstance() {
if (null == uploadUtil) {
uploadUtil = new UploadUtil();
}
return uploadUtil;
}


private static final String TAG = "UploadUtil";
private int readTimeOut = 10 * 1000; // 读取超时
private int connectTimeout = 10 * 1000; // 超时时间
/***
* 请求使用多长时间
*/
private static int requestTime = 0;


private static final String CHARSET = "utf-8"; // 设置编码


/***
* 上传成功
*/
public static final int UPLOAD_SUCCESS_CODE = 1;
/**
* 文件不存在
*/
public static final int UPLOAD_FILE_NOT_EXISTS_CODE = 2;
/**
* 服务器出错
*/
public static final int UPLOAD_SERVER_ERROR_CODE = 3;
protected static final int WHAT_TO_UPLOAD = 1;
protected static final int WHAT_UPLOAD_DONE = 2;


/**
* android上传文件到服务器

* @param filePath
*            需要上传的文件的路径
* @param fileKey
*            在网页上<input type=file name=xxx/> xxx就是这里的fileKey
* @param RequestURL
*            请求的URL
*/
public void uploadFile(String filePath, String fileKey, String RequestURL,
Map<String, String> param) {
if (filePath == null) {
sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE, "文件不存在");
return;
}
try {
File file = new File(filePath);
uploadFile(file, fileKey, RequestURL, param);
} catch (Exception e) {
sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE, "文件不存在");
e.printStackTrace();
return;
}
}


/**
* android上传文件到服务器

* @param file
*            需要上传的文件
* @param fileKey
*            在网页上<input type=file name=xxx/> xxx就是这里的fileKey
* @param RequestURL
*            请求的URL
*/
public void uploadFile(final File file, final String fileKey,
final String RequestURL, final Map<String, String> param) {
if (file == null || (!file.exists())) {
sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE, "文件不存在");
return;
}


Log.i(TAG, "请求的URL=" + RequestURL);
Log.i(TAG, "请求的fileName=" + file.getName());
Log.i(TAG, "请求的fileKey=" + fileKey);
new Thread(new Runnable() { // 开启线程上传文件
@Override
public void run() {
toUploadFile(file, fileKey, RequestURL, param);
}
}).start();


}


private void toUploadFile(File file, String fileKey, String RequestURL,
Map<String, String> param) {
String result = null;
requestTime = 0;


long requestTime = System.currentTimeMillis();
long responseTime = 0;


try {
URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(readTimeOut);
conn.setConnectTimeout(connectTimeout);
conn.setDoInput(true); // 允许输入流
conn.setDoOutput(true); // 允许输出流
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST"); // 请求方式
conn.setRequestProperty("Charset", CHARSET); // 设置编码
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary="
+ BOUNDARY);
// conn.setRequestProperty("Content-Type",
// "application/x-www-form-urlencoded");


/**
* 当文件不为空,把文件包装并且上传
*/
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
StringBuffer sb = null;
String params = "";


/***
* 以下是用于上传参数
*/
if (param != null && param.size() > 0) {
Iterator<String> it = param.keySet().iterator();
while (it.hasNext()) {
sb = null;
sb = new StringBuffer();
String key = it.next();
String value = param.get(key);
sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
sb.append("Content-Disposition: form-data; name=\"")
.append(key).append("\"").append(LINE_END)
.append(LINE_END);
sb.append(value).append(LINE_END);
params = sb.toString();
Log.i(TAG, key + "=" + params + "##");
dos.write(params.getBytes());
// dos.flush();
}
}


sb = null;
params = null;
sb = new StringBuffer();
/**
* 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
* filename是文件的名字,包含后缀名的 比如:abc.png
*/
sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
sb.append("Content-Disposition:form-data; name=\"" + fileKey
+ "\"; filename=\"" + "image.png" + "\"" + LINE_END);
sb.append("Content-Type:image/png" + LINE_END); // 这里配置的Content-type很重要的
// ,用于服务器端辨别文件的类型的
sb.append(LINE_END);
params = sb.toString();
sb = null;


Log.i(TAG, file.getName() + "=" + params + "##");
dos.write(params.getBytes());
/** 上传文件 */
InputStream is = new FileInputStream(file);
onUploadProcessListener.initUpload((int) file.length());
byte[] bytes = new byte[1024];
int len = 0;
int curLen = 0;
while ((len = is.read(bytes)) != -1) {
curLen += len;
dos.write(bytes, 0, len);
onUploadProcessListener.onUploadProcess(curLen);
}
is.close();


dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
.getBytes();
dos.write(end_data);
dos.flush();
/**
* 获取响应码 200=成功 当响应成功,获取响应的流
*/
int res = conn.getResponseCode();
responseTime = System.currentTimeMillis();
this.requestTime = (int) ((responseTime - requestTime) / 1000);
Log.e(TAG, "response code:" + res);
if (res == 200) {
Log.e(TAG, "request success");

BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
                String line = "";
StringBuffer sb1 = new StringBuffer();
int ss;
while(null != (line=br.readLine())){
sb1.append(line);
}
result = sb1.toString();
Log.e(TAG, "result : " + result);
sendMessage(UPLOAD_SUCCESS_CODE,result);
return;
} else {
Log.e(TAG, "request error");
sendMessage(UPLOAD_SERVER_ERROR_CODE, "上传失败:code=" + res);
return;
}
} catch (MalformedURLException e) {
sendMessage(UPLOAD_SERVER_ERROR_CODE,
"上传失败:error=" + e.getMessage());
e.printStackTrace();
return;
} catch (IOException e) {
sendMessage(UPLOAD_SERVER_ERROR_CODE,
"上传失败:error=" + e.getMessage());
e.printStackTrace();
return;
}
}


/**
* 发送上传结果

* @param responseCode
* @param responseMessage
*/
private void sendMessage(int responseCode, String responseMessage) {
onUploadProcessListener.onUploadDone(responseCode, responseMessage);
}


/**
* 下面是一个自定义的回调函数,用到回调上传文件是否完成

* @author shimingzheng

*/
public static interface OnUploadProcessListener {
/**
* 上传响应

* @param responseCode
* @param message
*/
void onUploadDone(int responseCode, String message);


/**
* 上传中

* @param uploadSize
*/
void onUploadProcess(int uploadSize);


/**
* 准备上传

* @param fileSize
*/
void initUpload(int fileSize);
}


private OnUploadProcessListener onUploadProcessListener;


public void setOnUploadProcessListener(
OnUploadProcessListener onUploadProcessListener) {
this.onUploadProcessListener = onUploadProcessListener;
}


public int getReadTimeOut() {
return readTimeOut;
}


public void setReadTimeOut(int readTimeOut) {
this.readTimeOut = readTimeOut;
}


public int getConnectTimeout() {
return connectTimeout;
}


public void setConnectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
}


/**
* 获取上传使用的时间

* @return
*/
public static int getRequestTime() {
return requestTime;
}


public static interface uploadProcessListener {


}


}

   这个是从网上找到的,大神已经包装成具类了 稍微改动就能使用了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值