图片上传服务器压缩工具类

这个是我整理调试的图片上传工具类;只需要图片路径方可;大家可以直接使用;希望可以帮助到大家;代码如下;

package com.wyy.twodimcode.push;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.DataOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;

import java.util.UUID;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.util.Log;

/**

*

* 上传工具类上传压缩;

* @author spring sky

* Email:[email protected]

* QQ:840950105

* MyName:石明政

*/

public class UploadUtil {

private static final String TAG = "uploadFile";

private static final int TIME_OUT = 10*1000; //超时时间

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

/**

* android上传文件到服务器

* @param file 需要上传的文件

* @param RequestURL 请求的rul

* @return 返回响应的内容

*/

public static String uploadFile(String file,String RequestURL)

{

String result = null;

String BOUNDARY = UUID.randomUUID().toString(); //边界标识 随机生成

String PREFIX = "--" , LINE_END = "\r\n";

String CONTENT_TYPE = "multipart/form-data"; //内容类型

try {

URL url = new URL(RequestURL);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setReadTimeout(TIME_OUT);

conn.setConnectTimeout(TIME_OUT);

conn.setDoInput(true); //允许输入流

conn.setDoOutput(true); //允许输出流

conn.setUseCaches(false); //不允许使用缓存

conn.setRequestMethod("POST"); //请求方式

conn.setRequestProperty("Charset", CHARSET); //设置编码

conn.setRequestProperty("connection", "keep-alive");

conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

if(file!=null){

/**

* 当文件不为空,把文件包装并且上传

*/

DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

InputStream is =compressImage(file);

byte[] bytes = new byte[9000];

int len = 0;

while((len=is.read(bytes))!=-1){

dos.write(bytes, 0, len);

}

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();

Log.e(TAG, "response code:"+res);

// if(res==200)

// {

Log.e(TAG, "request success");

InputStream input = conn.getInputStream();

StringBuffer sb1= new StringBuffer();

int ss ;

while((ss=input.read())!=-1)

{

sb1.append((char)ss);

}

result = sb1.toString();

Log.e(TAG, "result : "+ result);

// }

// else{

// Log.e(TAG, "request error");

// }

}

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return result;

}

public static InputStream compressImage(String file) {

Bitmap bitmap = BitmapFactory.decodeFile(file);

BitmapFactory.Options newOpts = new BitmapFactory.Options();

// 开始读入图片,此时把options.inJustDecodeBounds设为true

newOpts.inJustDecodeBounds = true;

bitmap = BitmapFactory.decodeFile(file, newOpts);

newOpts.inJustDecodeBounds = false;

int w = newOpts.outWidth;

int h = newOpts.outHeight;

// 设置分辨率

float hh = 800f;

float ww = 400f;

// 缩放比。由于是固定的比例缩放,只用高或者宽其中一个数据进行计算即可

int be = 1;

if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放

be = (int) (newOpts.outWidth / ww);

} else if (w < h && h > hh) {// 如果宽度大的话根据宽度固定大小缩放

be = (int) (newOpts.outHeight / hh);

}

if (be <= 0) {

be = 1;

}

newOpts.inSampleSize = be;// 设置缩放比例

// 重新读入图片,注意此时已经把newOpts.inJustDecodeBounds = false

bitmap = BitmapFactory.decodeFile(file, newOpts);

try {

// Bitmap bitmapyas=compressImage(bitmap);

return compressImage2(bitmap);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

return null;

}

}

public static InputStream compressImage2(Bitmap bitmap) throws Exception {

try {

ByteArrayOutputStream baos = new ByteArrayOutputStream();

bitmap.compress(Bitmap.CompressFormat.JPEG, 90, baos);

int options = 100;

int size = baos.toByteArray().length / 1024;

while (size > 40 && options > 0) {

baos.reset();// 重置baos即清空baos

options -= 10;// 每次都减少10

// 这里压缩options%,把压缩后的数据存放到baos中

bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);

size = baos.toByteArray().length / 1024;

}

// 把压缩后的数据baos存放到ByteArrayInputStream中

ByteArrayInputStream isBm = new ByteArrayInputStream(

baos.toByteArray());

// 把ByteArrayInputStream数据生成图片

// bitmap = BitmapFactory.decodeStream(isBm, null, null);

// if (size > 40) {

// return true;

// } else {

// return false;

// }

return isBm;

} catch (Exception e) {

throw e;

}

}

// private static Bitmap compressImage(Bitmap image) {

//

// ByteArrayOutputStream baos = new ByteArrayOutputStream();

// image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中

// int options = 100;

// while ( baos.toByteArray().length / 1024>1024) { //循环判断如果压缩后图片是否大于100kb,大于继续压缩

// baos.reset();//重置baos即清空baos

// image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中

// options -= 10;//每次都减少10

// }

// ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中

// Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片

// return bitmap;

// }

}

时间: 2024-07-28 23:16:22

图片上传服务器压缩工具类的相关文章

php图片上传服务器

原理是把图片上传到服务器的某个目录,然后在把他的名字存入数据库,或者不需要数据库这部分也行.读取的时候直接读取名字. HTML提交表格 <form method="post" action="upload_image_todb.php?name=<?php echo $username;?>" enctype="multipart/form-data"> <table> <h4>选择图片 <s

C#图片上传服务器缩放存储功能

项目需求上需要用户上传头像.本来是用第三方的插件的.但是很多都是收费的. 不过,我需要花这钱么?是不?所以网络上搜集了些资料.. 果然.这个世界 大神是很多很多的. 用了个免费插件. <script src="../Scripts/ajaxFileUpload.js" type="text/javascript"></script> 这玩意儿真心强大. 图片传到服务器了. 然后问题来了.图片要缩放.本来是想裁剪的. 不过.真心很烦..裁剪也做

JSP图片上传服务器

String operator = request.getParameter("operator"); //页面跳转的标识 String succeed="0";//记录是否上传成功 String fileName = "";//文件名字 String fileExt = ""; String filename1=""; if(operator!=null){ succeed="1";

Java - MultipartFile图片上传服务器,并且指定大小压缩

1 /*** 2 * 上传图片到服务器 并压缩 3 * 4 * @param myFile 文件 5 * @param request 6 * @return 7 */ 8 private Boolean UploadFile(MultipartFile myFile, int width, int height, HttpServletRequest request) { 9 Boolean sta = false; 10 InputStream is = null; 11 FileOutpu

Android 图片上传 工具提交类(三)

大体部分与post提交类似,只是需要设置 <pre name="code" class="java">MultipartEntity 代码如下: public class userUploadServiceImpl implements userUploadService{ @Override public String userUpload(InputStream in, Map<String, String> data, String p

图片上传服务器的而终极解决方案 【转载】

/** * 动态发布图片压缩 * * @param source_image 原图image * @param maxSize 限定的图片大小 * * @return 返回处理后的图片 */ - (NSData *)resetSizeOfImageData:(UIImage *)source_image maxSize:(NSInteger)maxSize; 先调整分辨率,分辨率可以自己设定一个值,大于的就缩小到这分辨率,小余的就保持原本分辨率.然后在根据最终大小来设置压缩比,比如传入maxSi

Android图片上传(头像裁切+原图原样)

还是那句话,最近项目比较忙拖了很久这篇文章终于完成了! 先看一下效果图: (一)头像裁切.上传服务器(效果图) 一般都是有圆形显示头像的,这里我自定义了一个ImageView,页面很干净但是看着很上档次吧! 点击头像从底部弹出一个对话框,提示用户头像来自相机或者相册,这都是常规流程. 上传完成后默认的"程序员头像"换成了萌妹子 (二)普通图片上传服务器(效果图) 模仿QQ空间发动态的布局随意捏造一个界面出来 点击添加图片从底部弹出一个对话框,提示用户图片来自相机或者相册,这也都是常规流

Ueditor 1.4.3.1 使用 ThinkPHP 3.2.3 的上传类进行图片上传

在 ThinkPHP 3.2.3 中集成百度编辑器最新版 Ueditor 1.4.3.1,同时将编辑器自带的上传类替换成 ThinkPHP 3.2.3 中的上传类. ① 下载编辑器(下载地址:http://ueditor.baidu.com/website/download.html),解压后放入项目根目录的 Data 目录并且将解压出来的目录重命名为 ueditor. 项目中的控制器 ./Application/Admin/Controller/BlogController.class.php

android选择图片或拍照图片上传到服务器(包括上传参数)

From:http://blog.csdn.net/springsky_/article/details/8213898具体上传代码: 1.选择图片和上传界面,包括上传完成和异常的回调监听 [java] view plaincopy package com.spring.sky.image.upload; import java.util.HashMap; import java.util.Map; import android.app.Activity; import android.app.