java上传图片裁剪
① thumbnails锲惧儚澶勭悊搴撶殑浣跨敤
thumbnails鏄疛ava涓涓浼樼镄勫浘镀忓勭悊搴掳纴鍙浠ュ瑰浘鐗囱繘琛屽帇缂┿佸姞姘村嵃銆佽佸壀銆佹洿鏀规牸寮忕瓑锷熻兘銆备笅闱涓哄ぇ瀹朵粙缁崭娇鐢ㄨ繖涓锲惧儚澶勭悊搴撱
璇存槑: 杩欎釜绫荤涓涓鏂规硶灏辨槸璁剧疆涓娄紶镄勫浘鐗囦缭瀛樼殑寰堣矾寰勶纴姣斿备笂浼犵殑锲剧墖閮戒缭瀛桦湪 E:/download/image/ 鐩褰曚笅锛涚浜屼釜鏂规硶灏辨槸璁剧疆锲剧墖淇濆瓨镄勫瓙鐩褰曪纴瀛愮洰褰曟槸镙规嵁浼犲叆镄剆hopId鐢熸垚镄勶纴铹跺悗灏嗘牴鐩褰曚笌瀛愮洰褰曟嫾鎺ヨ捣𨱒ュ氨鏄锲剧墖镄勪缭瀛樿矾寰勚
1銆丳athUtil.java:
璇存槑: 杩欎釜绫诲氨鏄鐢╰humbnails𨱒ュ勭悊锲剧墖镄勶纴杩涜屽帇缂╋纴铹跺悗锷犳按鍗帮纴铹跺悗鎶婄粡杩囦简澶勭悊镄勫浘鐗囦缭瀛桦埌dest鐩镙囱矾寰勪笅銆
2銆両mageUtil.java:
1銆 鎶婃按鍗板浘鐗噖atermark1.jpg娣诲姞鍒 src/test/resources 涓嬮溃銆
2銆乼est.java:
鍙浠ョ湅鍒板浘鐗囧凡缁忎缭瀛桦湪鐩镙囱矾寰勪笅浜嗭纴骞朵笖鏄闅忔満鐢熸垚镄勫悕瀛椼
镓揿紑锲剧墖鍙浠ョ湅鍒版按鍗板凡缁忓姞涓婂幓浜嗭纴铡熷浘澶у皬40kb锛屾搷浣滃悗镄勫浘鐗囧ぇ灏18k锛屼篃缁忚繃铡嬬缉浜嗐
娉ㄦ剰: 鐪熸e湪椤圭洰涓浣跨敤镄勬椂鍊欙纴ImageUtils涓鍙浠ョ洿鎺ヤ紶鍏MultipartFile瀵硅薄锛岃繖閲屼紶鍏File鏄涓轰简鏂逛究娴嬭瘯銆
thumbnails镄勪娇鐢ㄥ緢绠鍗曪纴灏辨槸寮曞叆渚濊禆锛岀劧钖庡氨浼犱竴涓闇瑕佽繘琛屾搷浣灭殑锲剧墖缁椤畠锛屾渶钖庣敤Thumbnails璋冩柟娉曡繘琛屽悇绉嶆搷浣溿备笂闱㈡堜緥鍙鑳界湅璧锋潵链夌偣楹荤储锛屽叾瀹炰笂闱㈢殑鍏朵粬鏂规硶閮芥槸鍑嗗囧伐浣滐纴姣斿傝剧疆锲剧墖淇濆瓨镄勮矾寰勚佺敓鎴愰殢链烘枃浠跺悕銆佸垱寤虹洰镙囱矾寰勭殑鏂囦欢澶圭瓑銆傚姛鑳戒篃涓嶆涓婇溃婕旂ず镄勯偅涓や釜锛岄渶浜呜В钥侀搧浠鍙浠ヨ嚜琛岀栌搴︼纴缃戜笂寰埚氥
② Java在jsp中 如何上传图片 在上传时可以取到图片大小并修改
用第三方工具去取 common-upload,具体取到图片的方法参考代码如下:
FileItemFactory fileItemFactory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(fileItemFactory);
upload.setHeaderEncoding("utf-8");
try {
List<FileItem> items = upload.parseRequest(request);
for (FileItem fileItem : items) {
System.out.println("fileName=" + fileItem.getFieldName());
//获取文件流
InputStream in = fileItem.getInputStream();
ServletContext context = getServletConfig().getServletContext();
String path = context.getRealPath("image");
System.out.println(path);
OutputStream out = new FileOutputStream(new File(path + "\\" + fileItem.getName()));
byte[] buffer = new byte[1024];
int len = 0;
while((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.close();
in.close();
System.out.println("写入完毕");
}
} catch (FileUploadException e) {
e.printStackTrace();
}
③ 上传图片,实现图片压缩 java.lang.IllegalArgumentException: Can't load standard profile: GRAY.pf
servlet代码:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jspsmart.upload.File;
import com.jspsmart.upload.Files;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
public class FileUpload extends HttpServlet {
//定义一个ServletConfig对象
private ServletConfig sc;
/**
* Constructor of the object.
*/
public FileUpload() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.flush();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
response.setContentType("text/html;charset=utf8");
PrintWriter out = response.getWriter();
//新建一个SmartUpload对象,接收用户上传文件
SmartUpload su = new SmartUpload();
su.initialize(sc, request, response);
su.upload();
Files fs = su.getFiles();
File frist = fs.getFile(0);
String filename = frist.getFileName();
String sctm = System.currentTimeMillis()+"";
//获得文件的扩展名
String ext = frist.getFileExt();
//把文件保存到服务器硬盘(以系统毫秒数命名)
frist.saveAs("/"+sctm+"."+ext);
String username = su.getRequest().getParameter("username");
System.out.println(username);
out.flush();
out.close();
} catch (SmartUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void init(ServletConfig sc) throws ServletException {
// Put your code here
this.sc = sc;
}
}
jsp代码:
<body>
<form action="fileUpload" method="post" enctype="multipart/form-data">
<input type="file" name="fileXXX" /><!-- 不懈这个name就接收不到,使用不到 -->
用户名:<input type="text" name="username" />
<br/>
<input type="submit" />
</form>
</body>
④ java上传图片 生成缩略图,如果上传的图片尺寸比较小就压缩处理
//将图按比例缩小。
public static BufferedImage resize(BufferedImage source, int targetW, int targetH) {
// targetW,targetH分别表示目标长和宽
int type = source.getType();
BufferedImage target = null;
double sx = (double) targetW / source.getWidth();
double sy = (double) targetH / source.getHeight();
//这里想实现在targetW,targetH范围内实现等比缩放。如果不需要等比缩放
//则将下面的if else语句注释即可
if(sx>sy)
{
sx = sy;
targetW = (int)(sx * source.getWidth());
}else{
sy = sx;
targetH = (int)(sy * source.getHeight());
}
if (type == BufferedImage.TYPE_CUSTOM) { //handmade
ColorModel cm = source.getColorModel();
WritableRaster raster = cm.(targetW, targetH);
boolean alphaPremultiplied = cm.isAlphaPremultiplied();
target = new BufferedImage(cm, raster, alphaPremultiplied, null);
} else
target = new BufferedImage(targetW, targetH, type);
Graphics2D g = target.createGraphics();
//smoother than exlax:
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY );
g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
g.dispose();
return target;
}
public static void saveImageAsJpg (String fromFileStr,String saveToFileStr,int width,int hight)
throws Exception {
BufferedImage srcImage;
// String ex = fromFileStr.substring(fromFileStr.indexOf("."),fromFileStr.length());
String imgType = "JPEG";
if (fromFileStr.toLowerCase().endsWith(".png")) {
imgType = "PNG";
}
// System.out.println(ex);
File saveFile=new File(saveToFileStr);
File fromFile=new File(fromFileStr);
srcImage = ImageIO.read(fromFile);
if(width > 0 || hight > 0)
{
srcImage = resize(srcImage, width, hight);
}
ImageIO.write(srcImage, imgType, saveFile);
}
public static void main (String argv[]) {
try{
//参数1(from),参数2(to),参数3(宽),参数4(高)
saveImageAsJpg("C:\\Documents and Settings\\xugang\\桌面\\tmr-06.jpg",
"C:\\Documents and Settings\\xugang\\桌面\\2.jpg",
120,120);
} catch(Exception e){
e.printStackTrace();
}
}
⑤ java图片裁剪后图片失真,这是怎么回事呢
输入和输出格式不对吧,比如用bmp读入,png输出。。。。
⑥ 如何在Java中进行图片剪裁 疯狂JAVA
packagetest;
importjava.awt.Color;
importjava.awt.Graphics2D;
importjava.awt.Image;
importjava.awt.geom.AffineTransform;
importjava.awt.image.AffineTransformOp;
importjava.awt.image.BufferedImage;
importjava.io.File;
importjava.io.IOException;
importjava.nio.Buffer;
importjavax.imageio.ImageIO;
importjavax.imageio.stream.ImageOutputStream;
/**
*裁剪、缩放图片工具类
*
*@authorCSDN没有梦想-何必远方
*/
publicclassImgUtils{
/**
*缩放图片方法
*
*@paramsrcImageFile
*要缩放的图片路径
*@paramresult
*缩放后的图片路径
*@paramheight
*目标高度像素
*@paramwidth
*目标宽度像素
*@parambb
*是否补白
*/
publicfinalstaticvoidscale(StringsrcImageFile,Stringresult,
intheight,intwidth,booleanbb){
try{
doubleratio=0.0;//缩放比例
Filef=newFile(srcImageFile);
BufferedImagebi=ImageIO.read(f);
Imageitemp=bi.getScaledInstance(width,height,bi.SCALE_SMOOTH);//bi.SCALE_SMOOTH
//选择图像平滑度比缩放速度具有更高优先级的图像缩放算法。
//计算比例
if((bi.getHeight()>height)||(bi.getWidth()>width)){
doubleratioHeight=(newInteger(height)).doubleValue()
/bi.getHeight();
doubleratioWhidth=(newInteger(width)).doubleValue()
/bi.getWidth();
if(ratioHeight>ratioWhidth){
ratio=ratioHeight;
}else{
ratio=ratioWhidth;
}
AffineTransformOpop=newAffineTransformOp(AffineTransform//仿射转换
.getScaleInstance(ratio,ratio),null);//返回表示剪切变换的变换
itemp=op.filter(bi,null);//转换源BufferedImage并将结果存储在目标
//BufferedImage中。
}
if(bb){//补白
BufferedImageimage=newBufferedImage(width,height,
BufferedImage.TYPE_INT_RGB);//构造一个类型为预定义图像类型之一的
//BufferedImage。
Graphics2Dg=image.createGraphics();//创建一个
//Graphics2D,可以将它绘制到此
//BufferedImage中。
g.setColor(Color.white);//控制颜色
g.fillRect(0,0,width,height);//使用Graphics2D上下文的设置,填充Shape
//的内部区域。
if(width==itemp.getWidth(null))
g.drawImage(itemp,0,(height-itemp.getHeight(null))/2,
itemp.getWidth(null),itemp.getHeight(null),
Color.white,null);
else
g.drawImage(itemp,(width-itemp.getWidth(null))/2,0,
itemp.getWidth(null),itemp.getHeight(null),
Color.white,null);
g.dispose();
itemp=image;
}
ImageIO.write((BufferedImage)itemp,"JPEG",newFile(result));//输出压缩图片
}catch(IOExceptione){
e.printStackTrace();
}
}
/**
*裁剪图片方法
*
*@parambufferedImage
*图像源
*@paramstartX
*裁剪开始x坐标
*@paramstartY
*裁剪开始y坐标
*@paramendX
*裁剪结束x坐标
*@paramendY
*裁剪结束y坐标
*@return
*/
(BufferedImagebufferedImage,
intstartX,intstartY,intendX,intendY){
intwidth=bufferedImage.getWidth();
intheight=bufferedImage.getHeight();
if(startX==-1){
startX=0;
}
if(startY==-1){
startY=0;
}
if(endX==-1){
endX=width-1;
}
if(endY==-1){
endY=height-1;
}
BufferedImageresult=newBufferedImage(endX-startX,endY-startY,
4);
for(intx=startX;x<endX;++x){
for(inty=startY;y<endY;++y){
intrgb=bufferedImage.getRGB(x,y);
result.setRGB(x-startX,y-startY,rgb);
}
}
returnresult;
}
publicstaticvoidmain(String[]args)throwsIOException{
Fileinput=newFile("input.jpg");
BufferedImageimg=ImageIO.read(input);
cropImage(img,10,10,20,20);
Fileoutput=newFile("output.jpg");
ImageIO.write(img,"jpg",output);
}
}
⑦ 服务器端 验证上传图片 格式的 正则 (java)
用字符串判断性能比正则好,
String imgExt = "jpg|jpeg|png|bmp|GIF|JPG|PNG|JPEG";
imgExt .indexOf("图片后缀") >= 0
或者 imgExt .contains("图片后缀")
这两种就可以