java代碼裁剪圖片 java圖片裁剪工具

如何在Java中進行圖片剪裁 瘋狂JAVA

package?test;

我們提供的服務有:成都網站建設、網站建設、微信公眾號開發、網站優化、網站認證、信州ssl等。為成百上千企事業單位解決了網站和推廣的問題。提供周到的售前咨詢和貼心的售后服務,是有科學管理、有技術的信州網站制作公司

import?java.awt.Color;

import?java.awt.Graphics2D;

import?java.awt.Image;

import?java.awt.geom.AffineTransform;

import?java.awt.image.AffineTransformOp;

import?java.awt.image.BufferedImage;

import?java.io.File;

import?java.io.IOException;

import?java.nio.Buffer;

import?javax.imageio.ImageIO;

import?javax.imageio.stream.ImageOutputStream;

/**

*?裁剪、縮放圖片工具類

*?

*?@author?CSDN?沒有夢想-何必遠方

*/

public?class?ImgUtils?{

/**

?*?縮放圖片方法

?*?

?*?@param?srcImageFile

?*????????????要縮放的圖片路徑

?*?@param?result

?*????????????縮放后的圖片路徑

?*?@param?height

?*????????????目標高度像素

?*?@param?width

?*????????????目標寬度像素

?*?@param?bb

?*????????????是否補白

?*/

public?final?static?void?scale(String?srcImageFile,?String?result,

int?height,?int?width,?boolean?bb)?{

try?{

double?ratio?=?0.0;?//?縮放比例

File?f?=?new?File(srcImageFile);

BufferedImage?bi?=?ImageIO.read(f);

Image?itemp?=?bi.getScaledInstance(width,?height,?bi.SCALE_SMOOTH);//?bi.SCALE_SMOOTH

//?選擇圖像平滑度比縮放速度具有更高優先級的圖像縮放算法。

//?計算比例

if?((bi.getHeight()??height)?||?(bi.getWidth()??width))?{

double?ratioHeight?=?(new?Integer(height)).doubleValue()

/?bi.getHeight();

double?ratioWhidth?=?(new?Integer(width)).doubleValue()

/?bi.getWidth();

if?(ratioHeight??ratioWhidth)?{

ratio?=?ratioHeight;

}?else?{

ratio?=?ratioWhidth;

}

AffineTransformOp?op?=?new?AffineTransformOp(AffineTransform//?仿射轉換

.getScaleInstance(ratio,?ratio),?null);//?返回表示剪切變換的變換

itemp?=?op.filter(bi,?null);//?轉換源?BufferedImage?并將結果存儲在目標

//?BufferedImage?中。

}

if?(bb)?{//?補白

BufferedImage?image?=?new?BufferedImage(width,?height,

BufferedImage.TYPE_INT_RGB);//?構造一個類型為預定義圖像類型之一的

//?BufferedImage。

Graphics2D?g?=?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",?new?File(result));?//?輸出壓縮圖片

}?catch?(IOException?e)?{

e.printStackTrace();

}

}

/**

?*?裁剪圖片方法

?*?

?*?@param?bufferedImage

?*????????????圖像源

?*?@param?startX

?*????????????裁剪開始x坐標

?*?@param?startY

?*????????????裁剪開始y坐標

?*?@param?endX

?*????????????裁剪結束x坐標

?*?@param?endY

?*????????????裁剪結束y坐標

?*?@return

?*/

public?static?BufferedImage?cropImage(BufferedImage?bufferedImage,

int?startX,?int?startY,?int?endX,?int?endY)?{

int?width?=?bufferedImage.getWidth();

int?height?=?bufferedImage.getHeight();

if?(startX?==?-1)?{

startX?=?0;

}

if?(startY?==?-1)?{

startY?=?0;

}

if?(endX?==?-1)?{

endX?=?width?-?1;

}

if?(endY?==?-1)?{

endY?=?height?-?1;

}

BufferedImage?result?=?new?BufferedImage(endX?-?startX,?endY?-?startY,

4);

for?(int?x?=?startX;?x??endX;?++x)?{

for?(int?y?=?startY;?y??endY;?++y)?{

int?rgb?=?bufferedImage.getRGB(x,?y);

result.setRGB(x?-?startX,?y?-?startY,?rgb);

}

}

return?result;

}

public?static?void?main(String[]?args)?throws?IOException?{

File?input?=?new?File("input.jpg");

BufferedImage?img?=?ImageIO.read(input);

cropImage(img,?10,?10,?20,?20);

File?output?=?new?File("output.jpg");

ImageIO.write(img,?"jpg",?output);

}

}

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圖片裁剪原理

總體思想

前臺網頁用js得到裁剪圖片的id及x y 寬度和高度

服務端根據id取出要裁剪的圖片

根據這些參數來生成裁剪的圖像 后臺代碼如下

java 代碼

package wodexiangce;

import java awt Rectangle;

import java awt image BufferedImage;

import java io File;

import java io FileInputStream;

import java io IOException;

import java util Iterator;

import javax imageio ImageIO;

import javax imageio ImageReadParam;

import javax imageio ImageReader;

import javax imageio stream ImageInputStream;

/**

*

*

*

*/

public class OperateImage {

// ===源圖片路徑名稱如 c:\ jpg

private String srcpath ;

// ===剪切圖片存放路徑名稱 如 c:\ jpg

private String subpath ;

// ===剪切點x坐標

private int x ;

private int y ;

// ===剪切點寬度

private int width ;

private int height ;

public OperateImage() {

}

public OperateImage( int x int y int width int height) {

this x = x ;

this y = y ;

this width = width ;

this height = height ;

}

/**

* 對圖片裁剪 并把裁剪完蛋新圖片保存

*/

public void cut() throws IOException {

FileInputStream is = null ;

ImageInputStream iis = null ;

try {

// 讀取圖片文件

is = new FileInputStream(srcpath)

/*

* 返回包含所有當前已注冊 ImageReader 的 Iterator 這些 ImageReader

* 聲稱能夠解碼指定格式 參數 formatName 包含非正式格式名稱

*(例如 jpeg 或 tiff )等

*/

Iterator ImageReader it = ImageIO getImageReadersByFormatName( jpg )

ImageReader reader = it next()

// 獲取圖片流

iis = ImageIO createImageInputStream(is)

/*

* piis:讀取源 true:只向前搜索 /p 將它標記為 只向前搜索

* 此設置意味著包含在輸入源中的圖像將只按順序讀取 可能允許 reader

* 避免緩存包含與以前已經讀取的圖像關聯的數據的那些輸入部分

*/

reader setInput(iis true ) ;

/*

* p描述如何對流進行解碼的類p 用于指定如何在輸入時從 Java Image I/O

* 框架的上下文中的流轉換一幅圖像或一組圖像 用于特定圖像格式的插件

* 將從其 ImageReader 實現的 getDefaultReadParam 方法中返回

* ImageReadParam 的實例

*/

ImageReadParam param = reader getDefaultReadParam()

/*

* 圖片裁剪區域 Rectangle 指定了坐標空間中的一個區域 通過 Rectangle 對象

* 的左上頂點的坐標(x y) 寬度和高度可以定義這個區域

*/

Rectangle rect = new Rectangle(x y width height)

// 提供一個 BufferedImage 將其用作解碼像素數據的目標

param setSourceRegion(rect)

/*

* 使用所提供的 ImageReadParam 讀取通過索引 imageIndex 指定的對象 并將

* 它作為一個完整的 BufferedImage 返回

*/

BufferedImage bi = reader read( param)

// 保存新圖片

ImageIO write(bi jpg new File(subpath))

} finally {

if (is != null )

is close() ;

if (iis != null )

iis close()

}

}

public int getHeight() {

return height;

}

public void setHeight( int height) {

this height = height;

}

public String getSrcpath() {

return srcpath;

}

public void setSrcpath(String srcpath) {

this srcpath = srcpath;

}

public String getSubpath() {

return subpath;

}

public void setSubpath(String subpath) {

this subpath = subpath;

}

public int getWidth() {

return width;

}

public void setWidth( int width) {

this width = width;

}

public int getX() {

return x;

}

public void setX( int x) {

this x = x;

}

public int getY() {

return y;

}

public void setY( int y) {

this y = y;

}

public static void main(String[] args) throws Exception {

String name = d:\ jpg ;

OperateImage o = new OperateImage( )

o setSrcpath(name)

o setSubpath( D:\ jpg )

o cut() ;

}

lishixinzhi/Article/program/Java/hx/201311/26771

java截取圖片

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

代碼半小時后出來!!!

……

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

import?java.awt.Color;

import?java.awt.Graphics;

import?java.awt.image.BufferedImage;

import?java.io.File;

import?java.io.IOException;

import?javax.imageio.ImageIO;

import?javax.swing.JApplet;

public?class?Test?extends?JApplet{

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

BufferedImage?mm,child;

CutImage?ci;

public?Test(){

try?{

mm=ImageIO.read(new?File(addrs));

}?catch?(IOException?e)?{

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

e.printStackTrace();

}

ci=new?CutImage(mm);

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

}

public?void?init(){

}

public?void?paint(Graphics?g){

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

}

}

import?java.awt.Image;

import?java.awt.image.BufferedImage;

public?class?CutImage?{

private?BufferedImage?img;

private?BufferedImage?child;

public?CutImage(){

}

public?CutImage(BufferedImage?im){

img=im;

}

public?CutImage(Image?im){

img=(BufferedImage)im;

}

public?void?setImg(BufferedImage?img)?{

this.img?=?img;

}

public?BufferedImage?getChildImage(int?x,int?y,int?width,int?height)?{

int?cw=width;

int?ch=height;

int?pw=img.getWidth();

int?ph=img.getHeight();

if(pwx+width){

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

cw=pw-x;

}

if(phy+height){

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

ch=ph-y;

}

child=new?BufferedImage(cw,ch,BufferedImage.TYPE_INT_ARGB?);

for(int?i=0;ich;i++){

for(int?j=0;jcw;j++){

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

}

}

return?child;

}

}

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

您好!請問用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代碼裁剪圖片 java圖片裁剪工具
網頁網址:http://m.kartarina.com/article6/dodssig.html

成都網站建設公司_創新互聯,為您提供網站維護ChatGPT自適應網站網站內鏈用戶體驗面包屑導航

廣告

聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯

網站托管運營
主站蜘蛛池模板: 亚洲AV无码专区国产乱码电影| 无码AV岛国片在线播放| 亚洲人成无码网WWW| 无码人妻丰满熟妇啪啪 | 激情射精爆插热吻无码视频| 一本色道无码道DVD在线观看| 无码精品国产va在线观看dvd| 国产亚洲?V无码?V男人的天堂 | 下载天堂国产AV成人无码精品网站 | 日本爆乳j罩杯无码视频| 无码137片内射在线影院 | 一本色道无码不卡在线观看| 人妻无码一区二区三区AV| 中文有无人妻vs无码人妻激烈| 97在线视频人妻无码| 国产羞羞的视频在线观看 国产一级无码视频在线 | 国产综合无码一区二区三区| 无码精品尤物一区二区三区| 久久久久亚洲av成人无码电影| 18禁无遮拦无码国产在线播放| 国产激情无码视频在线播放性色| 丰满亚洲大尺度无码无码专线| 久久精品国产亚洲AV无码娇色| 国产精品三级在线观看无码 | 国产精品无码免费专区午夜| 亚洲精品无码久久久久牙蜜区| 少妇精品无码一区二区三区| 亚洲精品中文字幕无码蜜桃| 亚洲AV无码一区二区三区在线观看 | 久久久久久亚洲av成人无码国产| 亚洲成A∨人片天堂网无码| 无码人妻精品一区二区蜜桃| AV无码精品一区二区三区| 日韩精品无码一区二区三区| 久久午夜无码鲁丝片直播午夜精品 | 国产精品爽爽va在线观看无码| 亚洲爆乳无码精品AAA片蜜桃| 中文字幕av无码无卡免费| 亚洲另类无码一区二区三区| 无码任你躁久久久久久老妇App| 久久久久久久人妻无码中文字幕爆 |