當前位置:首頁 » 文件管理 » java上傳圖片裁剪

java上傳圖片裁剪

發布時間: 2024-06-03 18:29:28

① 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("圖片後綴")
這兩種就可以

熱點內容
如何配置svi介面的ip地址 發布:2025-01-17 03:48:09 瀏覽:44
微軟怎麼解壓縮文件 發布:2025-01-17 03:43:06 瀏覽:203
有沒有手機可以用的java編譯器 發布:2025-01-17 03:38:56 瀏覽:542
手把手教你學c語言版 發布:2025-01-17 03:38:52 瀏覽:781
最優化遺傳演算法 發布:2025-01-17 03:35:24 瀏覽:546
四代飛度家用需要加裝哪些配置 發布:2025-01-17 03:34:28 瀏覽:876
安卓手機貓和老鼠怎麼換號 發布:2025-01-17 03:23:58 瀏覽:469
安卓系統怎麼下蝙蝠 發布:2025-01-17 03:20:07 瀏覽:19
加密解密文件 發布:2025-01-17 03:16:32 瀏覽:83
抗震柱加密區 發布:2025-01-17 03:03:06 瀏覽:134