『壹』 java中有截圖工具么
哎~要是你給我個分就好了!我前幾天剛剛做的!你拿去吧!
/*
作者:泡沫
地址:http://hi..com/av51
功能:用於截取圖片,方便快捷!
mail:yuhuidog#163.com (注意:其中#為@)
*/
import java.awt.AWTException;
『貳』 您好!請問用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對象
然後調用這個對象的 public BufferedImage getSubimage(int x,
int y,
int w,
int h)方法就可以了
『肆』 java中如何用滑鼠點擊截取一張圖片的某部分(希望有具體代碼)
用map標簽,在drw里用熱區,拖動就可以了,你試試
代碼會自動生成,如下:
<map
name="Map"
id="Map"><area
shape="rect"
coords="104,303,223,357"
href="http://www..com"
/>
</map>
你只要換掉104,303,223,357(圖片區域上下左右坐標的位置)和超鏈接地址即可
『伍』 如何用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實現網頁截圖,也就是「輸入一段網址,幾秒鍾過後就能截取一張網頁縮略圖」的效果。那麼,您至少有3種方式可以選擇。
1、最直接的方式——使用Robot
方法詳解:該方法利用Robat提供的強大桌面操作能力,硬性調用瀏覽器打開指定網頁,並將網頁信息保存到本地。
優勢:簡單易用,不需要任何第三方插件。
缺點:不能同時處理大量數據,技術含量過低,屬於應急型技巧。
實現方法:使用如下代碼即可。
[java] view plain
public static void main(String[] args) throws MalformedURLException,
IOException, URISyntaxException, AWTException {
//此方法僅適用於JdK1.6及以上版本
Desktop.getDesktop().browse(
new URL("http://google.com/intl/en/").toURI());
Robot robot = new Robot();
robot.delay(10000);
Dimension d = new Dimension(Toolkit.getDefaultToolkit().getScreenSize());
int width = (int) d.getWidth();
int height = (int) d.getHeight();
//最大化瀏覽器
robot.keyRelease(KeyEvent.VK_F11);
robot.delay(2000);
Image image = robot.createScreenCapture(new Rectangle(0, 0, width,
height));
BufferedImage bi = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = bi.createGraphics();
g.drawImage(image, 0, 0, width, height, null);
//保存圖片
ImageIO.write(bi, "jpg", new File("google.jpg"));
}
2、最常規的方式——利用JNI,調用第三方C/C++組件
方法詳解:目前來講,Java領域對於網頁截圖組件的開發明顯不足(商機?),當您需要完成此種操作時,算得上碰到了Java的軟肋。但是,眾所周知Java也擁有強大的JNI能力,可以輕易將C/C++開發的同類組件引為己用。不懂可以扣五七八零二四一四四
優勢:實現簡單,只需要封裝對應的DLL文件,就可以讓Java實現同類功能。
劣勢:同其他JNI實現一樣,在跨平台時存在隱患,而且您的程序將不再屬於純Java應用。
『柒』 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報春到你的電腦上了。下面程序的運行效果吧!
『捌』 如何在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截取網址圖片路徑到指定目錄。並改寫路徑地址
1你想把src裡面的jpg圖片保存到本地某個目錄路徑裡面
2你再把你保存的這個目錄路徑設置回去
3抓取網頁圖片
importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.io.OutputStream;
importjava.net.URL;
importjava.net.URLConnection;
importjava.util.ArrayList;
importjava.util.Calendar;
importjava.util.List;
importjava.util.regex.Matcher;
importjava.util.regex.Pattern;
importcom.sun.xml.internal.fastinfoset.stax.events.Util;
publicclassCatchPicture{
publicstaticvoidmain(String[]args){
//TODOAuto-generatedmethodstub
//定義抓取圖片的正則表達式
Stringregular="[*]<b>.*?</b><br/><imgsrc="(.*?)"border=0alt='(.*?)'style=".*?"class=".*?">
";
List<Picture>list=newCatchPicture().lookWeiboPic("http://gaoxiao.jokeji.cn/GrapHtml/dongtai/20120921221658.htm","GBK",regular,"2,1");
System.out.println(list.size());
}
//根據URL查看網站上的圖片
publicList<Picture>lookWeiboPic(Stringurl,Stringcharset,Stringregular,StringattIndex){
List<Picture>list=newArrayList<Picture>();
try{
//獲取填寫的url
//判斷所屬網站獲取正則表達式
//獲取圖片存放到list集合
if(!Util.isEmptyString(url)){
Stringhtmls=getPageSource(url.trim(),charset);
Patternpattern=null;
pattern=Pattern.compile(regular.trim());
if(!Util.isEmptyString(htmls)){
Matchermatcher=pattern.matcher(htmls);
//得到參數屬性順序
String[]sort=regular.trim().split(",");//下標:0表示標題title,1表示圖片路徑
//判斷後綴後得到網站的請求頭部http://www.moonbasa.com/p-032111106.html-->得到http://www.moonbasa.com
String[]suffix;
suffix=url.trim().split("cn");
Stringhttphread="";
if(suffix.length>1){
httphread=suffix[0]+"cn";
}else{
suffix=url.trim().split("com");
httphread=suffix[0]+"com";
}
//循環匹配找到的
while(matcher.find()){
Picturepicture=newPicture();
//匹配出title
if(-1==Integer.parseInt(sort[0])){
//頁面上抓不到標題
picture.setTitle("");
}else{
//去標題的#
Stringtitle=matcher.group(Integer.parseInt(sort[0])).replace("#","");
picture.setTitle(title);
}
//匹配出source
if(-1==Integer.parseInt(sort[1])){
//頁面上抓不到圖片路徑
picture.setSource("");
}else{
StringwebImgUrl=matcher.group(Integer.parseInt(sort[1]));
//判斷是絕對路徑還是相對路徑
String[]pathType=webImgUrl.split(":");
if(pathType.length>1){
//絕對路徑
picture.setSource(webImgUrl);
}else{
//判斷相對路徑是否含有..
pathType=webImgUrl.split("\.\.");
if(pathType.length>1){
picture.setSource(httphread+pathType[1]);
}else{
if(webImgUrl.startsWith("/")){
picture.setSource(httphread+pathType[0]);
}else{
picture.setSource(httphread+"/"+pathType[0]);
}
}
}
}
StringupPath=upload(picture.getSource(),"d:\image\");
picture.setUpPath(upPath);
list.add(picture);
}//--endwhile
}
}
}catch(Exceptione){
e.printStackTrace();
}
returnlist;
}
/**
*根據網路路徑獲取頁面源碼
*@parampageUrl
*@paramencoding
*@return
*/
publicStringgetPageSource(StringpageUrl,Stringencoding){
StringBuffersb=newStringBuffer();
try{
//構建一URL對象
URLurl=newURL(pageUrl);
//使用openStream得到一輸入流並由此構造一個BufferedReader對象
BufferedReaderin=newBufferedReader(newInputStreamReader(url
.openStream(),encoding));
Stringline;
//讀取www資源
while((line=in.readLine())!=null){
sb.append(line);
sb.append(" ");
}
in.close();
}catch(Exceptionex){
System.err.println(ex);
}
returnsb.toString();
}
/**
*上傳圖片
*@paramurlStr
*@parampath
*@return
*@throwsException
*/
publicStringupload(StringurlStr,Stringpath)throwsException{
Calendarcalendar=Calendar.getInstance();
Stringmonth=calendar.get(Calendar.YEAR)+"/"
+(calendar.get(Calendar.MONTH)+1);
Stringfilename=java.util.UUID.randomUUID().toString()
+getExtension(urlStr);
path=path+month+"/";
download(urlStr,path,filename);
returnpath+month+"/"+filename;
}
/**
*根據路徑下載圖片然後保存到對應的目錄下
*@paramurlString
*@paramfilename
*@paramsavePath
*@return
*@throwsException
*/
publicvoiddownload(StringurlString,Stringfilename,StringsavePath)throwsException{
//構造URL
URLurl=newURL(urlString);
//打開連接
URLConnectioncon=url.openConnection();
//設置請求的路徑
con.setConnectTimeout(5*1000);
//輸入流
InputStreamis=con.getInputStream();
//1K的數據緩沖
byte[]bs=newbyte[1024];
//讀取到的數據長度
intlen;
//輸出的文件流
Filesf=newFile(savePath);
if(!sf.exists()){
sf.mkdirs();
}
OutputStreamos=newFileOutputStream(sf.getPath()+"\"+filename);
//開始讀取
while((len=is.read(bs))!=-1){
os.write(bs,0,len);
}
//完畢,關閉所有鏈接
os.close();
is.close();
}
/**
*根據文件名獲取文件的後綴名
*@paramfileUrl
*@return
*/
publicStringgetExtension(StringfileUrl){
returnfileUrl.substring(fileUrl.lastIndexOf("."),fileUrl.length());
}
}