當前位置:首頁 » 編程語言 » java圖片裁剪

java圖片裁剪

發布時間: 2022-05-09 20:49:56

java後台裁剪圖片

BufferedImage ImageIO File 差不多了。

  1. 讀取文件 BufferedImage bi = ImageIO.read(new File(filepath));

  2. 裁剪 BufferedImage sub = bi.getSubImage(bi,x,y,w,h);

  3. 寫文件ImageIO.write(sub,"PNG",new File(filepath));

⑵ 您好!請問用java怎麼將截取png的圖片中間一部分,以及如何壓縮一個png圖片

  • getSubimage方法是進行圖片裁剪。

舉例:
public static void main(String[] args) {
try {
//從特定文件載入
BufferedImage bi = ImageIO.read(new File("c:\test.png"));
bi.getSubimage(0, 0, 10, 10);//前兩個值是坐標位置X、Y,後兩個是長和寬
} catch (IOException e) {
e.printStackTrace();
}
}

  • 以下是進行的圖片壓縮,涉及到多個工具類。

/**
* 圖片工具類
* 壓縮圖片大小
* @author Cyw
* @version 1.0
*/
public class ZIPImage {

private File file = null;

private String outPutFilePath;

private String inPutFilePath;

private String inPutFileName;

private boolean autoBuildFileName;

private String outPutFileName;

private int outPutFileWidth = 100; // 默認輸出圖片寬

private int outPutFileHeight = 100; // 默認輸出圖片高

private static boolean isScaleZoom = true; // 是否按比例縮放

public ZIPImage() {
outPutFilePath = "";
inPutFilePath = "";
inPutFileName = "";
autoBuildFileName = true;
outPutFileName = "";
}

/**
*
* @param ipfp
* 源文件夾路徑
* @param ipfn
* 源文件名
* @param opfp
* 目標文件路徑
* @param opfn
* 目標文件名
*/
public ZIPImage(String ipfp, String ipfn, String opfp, String opfn) {
outPutFilePath = opfp;
inPutFilePath = ipfp;
inPutFileName = ipfn;
autoBuildFileName = true;
outPutFileName = opfn;
}

/**
*
* @param ipfp
* 源文件夾路徑
* @param ipfn
* 源文件名
* @param opfp
* 目標文件路徑
* @param opfn
* 目標文件名
* @param aBFN
* 是否自動生成目標文件名
*/
public ZIPImage(String ipfp, String ipfn, String opfp, String opfn,
boolean aBFN) {
outPutFilePath = opfp;
inPutFilePath = ipfp;
inPutFileName = ipfn;
autoBuildFileName = aBFN;
outPutFileName = opfn;
}

public boolean isAutoBuildFileName() {
return autoBuildFileName;
}

public void setAutoBuildFileName(boolean autoBuildFileName) {
this.autoBuildFileName = autoBuildFileName;
}

public String getInPutFilePath() {
return inPutFilePath;
}

public void setInPutFilePath(String inPutFilePath) {
this.inPutFilePath = inPutFilePath;
}

public String getOutPutFileName() {
return outPutFileName;
}

public void setOutPutFileName(String outPutFileName) {
this.outPutFileName = outPutFileName;
}

public String getOutPutFilePath() {
return outPutFilePath;
}

public void setOutPutFilePath(String outPutFilePath) {
this.outPutFilePath = outPutFilePath;
}

public int getOutPutFileHeight() {
return outPutFileHeight;
}

public void setOutPutFileHeight(int outPutFileHeight) {
this.outPutFileHeight = outPutFileHeight;
}

public int getOutPutFileWidth() {
return outPutFileWidth;
}

public void setOutPutFileWidth(int outPutFileWidth) {
this.outPutFileWidth = outPutFileWidth;
}

public boolean isScaleZoom() {
return isScaleZoom;
}

public void setScaleZoom(boolean isScaleZoom) {
this.isScaleZoom = isScaleZoom;
}

public String getInPutFileName() {
return inPutFileName;
}

public void setInPutFileName(String inPutFileName) {
this.inPutFileName = inPutFileName;
}

/**
* 壓縮圖片大小
*
* @return boolean
*/
public boolean compressImage() {
boolean flag = false;

try {
if (inPutFilePath.trim().equals("")) {
throw new NullPointerException("源文件夾路徑不存在。");
}
if (inPutFileName.trim().equals("")) {
throw new NullPointerException("圖片文件路徑不存在。");
}
if (outPutFilePath.trim().equals("")) {
throw new NullPointerException("目標文件夾路徑地址為空。");
} else {
if (!ZIPImage.mddir(outPutFilePath)) {
throw new FileNotFoundException(outPutFilePath
+ " 文件夾創建失敗!");
}
}

if (this.autoBuildFileName) { // 自動生成文件名
String tempFile[] = getFileNameAndExtName(inPutFileName);
outPutFileName = tempFile[0] + "_cyw." + tempFile[1];
compressPic();
} else {
if (outPutFileName.trim().equals("")) {
throw new NullPointerException("目標文件名為空。");
}
compressPic();
}

} catch (Exception e) {
flag = false;
e.printStackTrace();
return flag;
}

return flag;
}

// 圖片處理
private void compressPic() throws Exception {
try {
// 獲得源文件
file = new File(inPutFilePath + inPutFileName);
if (!file.exists()) {
throw new FileNotFoundException(inPutFilePath + inPutFileName
+ " 文件不存在!");
}
Image img = ImageIO.read(file);
// 判斷圖片格式是否正確
if (img.getWidth(null) == -1) {
throw new Exception("文件不可讀!");
} else {
int newWidth;
int newHeight;
// 判斷是否是等比縮放
if (ZIPImage.isScaleZoom == true) {
// 為等比縮放計算輸出的圖片寬度及高度
double rate1 = ((double) img.getWidth(null))
/ (double) outPutFileWidth + 0.1;
double rate2 = ((double) img.getHeight(null))
/ (double) outPutFileHeight + 0.1;

// 根據縮放比率大的進行縮放控制
double rate = rate1 > rate2 ? rate1 : rate2;

newWidth = (int) (((double) img.getWidth(null)) / rate);
newHeight = (int) (((double) img.getHeight(null)) / rate);

} else {
newWidth = outPutFileWidth; // 輸出的圖片寬度
newHeight = outPutFileHeight; // 輸出的圖片高度
}

BufferedImage tag = new BufferedImage((int) newWidth,
(int) newHeight, BufferedImage.TYPE_INT_RGB);

/*
* Image.SCALE_SMOOTH 的縮略演算法 生成縮略圖片的平滑度的 優先順序比速度高 生成的圖片質量比較好 但速度慢
*/
tag.getGraphics().drawImage(
img.getScaledInstance(newWidth, newHeight,
Image.SCALE_SMOOTH), 0, 0, null);

FileOutputStream out = new FileOutputStream(outPutFilePath
+ outPutFileName);

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
out.close();

}
} catch (IOException ex) {
ex.printStackTrace();
}
}

/**
* 創建文件夾目錄
*
* @param filePath
* @return
* @throws Exception
*/
@SuppressWarnings("unused")
private static boolean mddir(String filePath) throws Exception {
boolean flag = false;
File f = new File(filePath);
if (!f.exists()) {
flag = f.mkdirs();
} else {
flag = true;
}
return flag;
}

/**
* 獲得文件名和擴展名
*
* @param fullFileName
* @return
* @throws Exception
*/
private String[] getFileNameAndExtName(String fullFileName)
throws Exception {
String[] fileNames = new String[2];
if (fullFileName.indexOf(".") == -1) {
throw new Exception("源文件名不正確!");
} else {
fileNames[0] = fullFileName.substring(0, fullFileName
.lastIndexOf("."));
fileNames[1] = fullFileName
.substring(fullFileName.lastIndexOf(".") + 1);
}
return fileNames;
}

public Image getSourceImage() throws IOException{
//獲得源文件
file = new File(inPutFilePath + inPutFileName);
if (!file.exists()) {
throw new FileNotFoundException(inPutFilePath + inPutFileName
+ " 文件不存在!");
}
Image img = ImageIO.read(file);
return img;
}

/*
* 獲得圖片大小
* @path :圖片路徑
*/
public long getPicSize(String path) {
File file = new File(path);
return file.length();
}

}

//下面是測試程序

package com.sun.util.cyw;

import java.awt.Image;
import java.io.IOException;

public class ImageTest {
public static void main(String[] args) throws IOException {
ZIPImage zip=new ZIPImage("d:\","1.jpg","d:\test\","處理後的圖片.jpg",false);
zip.setOutPutFileWidth(1000);
zip.setOutPutFileHeight(1000);

Image image=zip.getSourceImage();
long size=zip.getPicSize("d:\1.jpg");
System.out.println("處理前的圖片大小 width:"+image.getWidth(null));
System.out.println("處理前的圖片大小 height:"+image.getHeight(null));
System.out.println("處理前的圖片容量:"+ size +" bit");

zip.compressImage();
}
}

⑶ java怎麼剪裁圖片

BufferedImage類有一個getSubimage()方法,以下來自API

public BufferedImage getSubimage(int x,
int y,
int w,
int h)

返回由指定矩形區域定義的子圖像。返回的 BufferedImage 與源圖像共享相同的數據數組。

參數:
x - 指定矩形區域左上角的 X 坐標
y - 指定矩形區域左上角的 Y 坐標
w - 指定矩形區域的寬度
h - 指定矩形區域的高度
返回:
BufferedImage,它是此 BufferedImage 的子圖像。
拋出:
RasterFormatException - 如果指定區域不包含在此 BufferedImage 中。

⑷ 如何在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中使用setClip()裁剪不規則圖形

GeneralPath path = new GeneralPath();
path.moveTo(x1, y1);
path.lineTo(x2, y2);
path.lineTo(x3, y3);
path.closePath();
g.setClip(path);
可以通過這個設置

⑹ 請問用Java 怎樣實現摳圖功能。比如圖片是一塊石頭放在一張紙上,怎樣

1、用ps打開兩張圖片。
2、在工具里選擇「移動工具」,按住滑鼠左鍵把第二個圖片拖動到第一個圖片里。由於第二張的像素有點大,所以會把原來的圖片覆蓋住的,通過滑鼠稍微移動一下。
3、按ctrl+t(自由變換快捷鍵),圖片的四周出現了可以調節的橫線,按住shift拖動圖片的一個角可以進行等比例縮放,這張圖太大了,所以等比例縮小一點。調整為合適的大小,放到合適的地方。調整完畢,按enter鍵確認。
4、在右下角的圖層面板里點擊第三個按鈕(添加矢量蒙板),為第二個圖層添加一個蒙板。
5、可以看到在「工具」里,前景色和背景色默認修改為了白色和黑色。
6、然後選擇工具里的「漸變」工具。可以看到,上方工具欄出現了漸變的一些設置。因為前景色為白色,背景色為黑色,所以默認是白色到黑色的漸變條。後面分別設置為徑向漸變,正常模式,百分之百不透明度,反向不打勾。
7、點擊白色到黑色的漸變條,進入漸變編輯器。
8、把左側下方的白色滑塊拖到中間,可以在下方的位置處直接填寫百分之50。
9、把滑鼠放在左側的滑動條下方,會出現「點按可添加色標」。
10、點擊一下,出現一個新的色塊,為白色。把它拖動到最左邊,可以直接填寫百分之0。
11、選中最左邊的白色色塊,點擊一下下面的顏色後面的白色,彈出「選擇色標顏色」的窗口。在裡面選擇純黑色。點擊「確定」。這樣就把白色改成了黑色。漸變色變成了黑-白-黑。點擊「確定」。
12、可以看到上面確實變成了黑色-白色-黑色漸變。
13、一隻手按住shift鍵,一隻手按住滑鼠左鍵在圖片上拉出一條直線(按住shift鍵是保證水平)。
14、松開手,蒙板就起作用了,這是利用了蒙板狀態下,黑色隱藏,白色顯示的特點。
15、然後稍加修飾。選擇工具里的「矩形選框工具」,選中要裁剪的部分。
16、點擊「圖像」,選擇「裁剪」。
17、圖片被裁剪,裁剪完成後按ctrl+d取消選中狀態,或者可以點擊右鍵,選擇「取消」。
18、、這樣就實現了兩張圖片的合成。利用蒙板和漸變色合成的方式的好處是第二個圖片可以保留一部分的背景,有一種融入的感覺。如果採用摳圖合並的方法,一般是給人物換背景圖,技術要求比較高。

⑺ 我有一個簽名圖片如何用java代碼裁剪掉空白區域

用imageIO 讀取進入BufferedImage,檢測圖片非空白大小,建立新的BufferedImage,拷貝非空白區至新的BufferedImage, 用imageIO 再次保存。

⑻ java圖片裁剪後圖片失真,這是怎麼回事呢

輸入和輸出格式不對吧,比如用bmp讀入,png輸出。。。。

⑼ java怎麼使用剪切板

Java提供兩種類型的剪貼板:系統的和本地的.

本地剪貼板只在當前虛擬機中有效.Java允許多個本地剪貼板同時存在,可以方便地通過剪貼板的名稱來進行存取訪問.

系統剪貼板與同等操作系統直接關連,允許應用程序與運行在該操作系統下的其它程序之間進行信息交換.

在進一步深入之前,先看看與剪貼板相同的java類,這些類主要包含在java.awt.datatransfer包中,主要有以下幾種:

Clipboard類: 此類實現一種使用剪切/復制/粘貼操作傳輸數據的機制.

ClipboardOwner介面: 任何處理剪貼板的類都必須實現該介面.該介面用於剪貼板中的原始數據被替換時發出通知.

Dataflavor類: 提供有關數據的元信息,通常用於訪問剪切板上的數據。

Transferable介面: 為傳輸操作提供數據所使用的類的介面

StringSelection類: 實現傳輸String所需能力的Transferable

Clipboard類:方法

1.String getName(); 返回剪切板對象的名字

2.setContents(Transferable contents,ClipOwner owner);

講剪切板的內容設置到指定的Transferable對象,並將指定的剪切板所有者作為新內容的所有者注冊

3.Transferable getContents(null);

返回表示剪貼板當前內容的 transferable 對象。無則null

4.DataFlavor[] getAvailableDataFlavors();

返回 DataFlavor 的數組,其中提供了此剪貼板的當前內容。無則null

5.boolean isDataFlavorAvailable(DataFlavor flavor);

返回是否能夠以指定的 DataFlavor 形式提供此剪貼板的當前內容。

6.Object getData(DataFlavor flavor);

返回一個對象,表示此剪貼板中指定 DataFlavor 類型的當前內容。

Transferable介面:

屬性:

1.stringFlavor:字元串數據

2.imageFlavor:圖片數據

方法:

1.Object getTransferData(DataFlavor flavor)

返回一個對象,該對象表示將要被傳輸的數據。

2.()

返回 DataFlavor 對象的數組,指示可用於提供數據的 flavor。

3.boolean isDataFlavorSupported(DataFlavor flavor)

返回此對象是否支持指定的數據 flavor。

例子:1.往剪切板裡面寫文本數據

Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

Transferable trandata = new StringSelection("4654654");

clipboard.setContents(trandata, null);

2.獲取剪切板中的內容(文本數據)

Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

Transferable clipT = clipboard.getContents(null);
//獲取文本中的Transferable對象

if(clipT!=null){

if(clipT.isDataFlavorSupported(DataFlavor.stringFlavor))
//判斷內容是否為文本類型stringFlavor

return (String)clipT.getTransferData(DataFlavor.stringFlavor);
//返回指定flavor類型的數據

⑽ java截取圖片

呵呵,很明確的告訴你:可以!

代碼半小時後出來!!!

……

終於出來了(呵呵,好像超過了半小時哈)且看代碼:

importjava.awt.Color;

importjava.awt.Graphics;

importjava.awt.image.BufferedImage;

importjava.io.File;

importjava.io.IOException;

importjavax.imageio.ImageIO;

importjavax.swing.JApplet;

publicclassTestextendsJApplet{

Stringaddrs="F:\images\mm.bmp";//改成自己的圖片路徑

BufferedImagemm,child;

CutImageci;

publicTest(){

try{

mm=ImageIO.read(newFile(addrs));

}catch(IOExceptione){

System.out.println("圖片讀取失敗!");

e.printStackTrace();

}

ci=newCutImage(mm);

child=ci.getChildImage(50,0,150,220);

}

publicvoidinit(){

}

publicvoidpaint(Graphicsg){

g.setColor(Color.red);

g.drawString("原圖:",0,10);

g.drawImage(mm,20,10,this);

g.drawString("ci.getChildImage(50,0,150,220)截取後的圖片",mm.getWidth()+30,10);

g.drawImage(child,mm.getWidth()+50,20,this);

}

}

importjava.awt.Image;

importjava.awt.image.BufferedImage;

publicclassCutImage{

privateBufferedImageimg;

privateBufferedImagechild;

publicCutImage(){

}

publicCutImage(BufferedImageim){

img=im;

}

publicCutImage(Imageim){

img=(BufferedImage)im;

}

publicvoidsetImg(BufferedImageimg){

this.img=img;

}

(intx,inty,intwidth,intheight){

intcw=width;

intch=height;

intpw=img.getWidth();

intph=img.getHeight();

if(pw<x+width){

System.out.println("給出的參數超出原圖片的范圍!程序會自動減小寬度或高度");

cw=pw-x;

}

if(ph<y+height){

System.out.println("給出的參數超出原圖片的范圍!程序會自動減小寬度或高度");

ch=ph-y;

}

child=newBufferedImage(cw,ch,BufferedImage.TYPE_INT_ARGB);

for(inti=0;i<ch;i++){

for(intj=0;j<cw;j++){

child.setRGB(j,i,img.getRGB(x+j,y+i));

}

}

returnchild;

}

}

呵呵,希望樓主能夠滿意哦,如果你願意的話,稍微改一下代碼就可以把截取的圖片child報春到你的電腦上了。下面程序的運行效果吧!

熱點內容
瑞虎三都有哪些配置 發布:2025-05-11 05:05:08 瀏覽:949
mc非正版伺服器怎麼做 發布:2025-05-11 05:04:54 瀏覽:307
安卓手機九宮格忘記密碼怎麼解 發布:2025-05-11 05:00:30 瀏覽:595
安卓手機拼多多怎麼解綁銀行卡 發布:2025-05-11 05:00:25 瀏覽:686
校園網可以搭建伺服器地址 發布:2025-05-11 04:54:40 瀏覽:785
noip演算法 發布:2025-05-11 04:53:51 瀏覽:50
有什麼我的世界伺服器啟動器 發布:2025-05-11 04:50:41 瀏覽:296
寫shell腳本 發布:2025-05-11 04:37:41 瀏覽:935
電腦伺服器打開有什麼用 發布:2025-05-11 04:36:49 瀏覽:98
sqlserver2008查詢時間 發布:2025-05-11 04:15:28 瀏覽:386