java图片裁剪
⑴ java后台裁剪图片
BufferedImage ImageIO File 差不多了。
读取文件 BufferedImage bi = ImageIO.read(new File(filepath));
裁剪 BufferedImage sub = bi.getSubImage(bi,x,y,w,h);
写文件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报春到你的电脑上了。下面程序的运行效果吧!