JAVA对图片操作(一)

简介: JAVA对图片操作

package com.test.grahpic;

import java.awt.AlphaComposite;

import java.awt.Color;

import java.awt.Font;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.Point;

import java.awt.Rectangle;

import java.awt.color.ColorSpace;

import java.awt.image.BufferedImage;

import java.awt.image.ColorConvertOp;

import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.FileReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.util.Iterator;

import java.util.List;


import javax.imageio.ImageIO;

import javax.imageio.ImageReadParam;

import javax.imageio.ImageReader;

import javax.imageio.stream.ImageInputStream;


import com.sun.image.codec.jpeg.JPEGCodec;

import com.sun.image.codec.jpeg.JPEGImageEncoder;


/**

*

* 创建日期 2016-2-29

*/

public class OperateImage{


public OperateImage() {

super();

}


/**

* 对图片裁剪,并把裁剪新图片保存

* @param srcPath 读取源图片路径

* @param toPath写入图片路径

* @param x 剪切起始点x坐标

* @param y 剪切起始点y坐标

* @param width 剪切宽度

* @param height剪切高度

* @param readImageFormat  读取图片格式

* @param writeImageFormat 写入图片格式

* @throws IOException

*/

   public void cropImage(String srcPath,String toPath,

   int x,int y,int width,int height,

   String readImageFormat,String writeImageFormat) throws IOException{  

       FileInputStream fis = null ;

       ImageInputStream iis =null ;

       try{  

           //读取图片文件

       fis = new FileInputStream(srcPath);

           Iterator it = ImageIO.getImageReadersByFormatName(readImageFormat);

           ImageReader reader = (ImageReader) it.next();

           //获取图片流

           iis = ImageIO.createImageInputStream(fis);  

           reader.setInput(iis,true) ;

           ImageReadParam param = reader.getDefaultReadParam();

           //定义一个矩形

           Rectangle rect = new Rectangle(x, y, width, height);

           //提供一个 BufferedImage,将其用作解码像素数据的目标。

           param.setSourceRegion(rect);

           BufferedImage bi = reader.read(0,param);                

           //保存新图片

           ImageIO.write(bi, writeImageFormat, new File(toPath));    

       }finally{

           if(fis!=null)

           fis.close();      

           if(iis!=null)

              iis.close();

       }

   }


 /**

    * 按倍率缩小图片

    * @param srcImagePath 读取图片路径

    * @param toImagePath 写入图片路径

    * @param widthRatio 宽度缩小比例

    * @param heightRatio 高度缩小比例

    * @throws IOException

    */

   public void reduceImageByRatio(String srcImagePath,String toImagePath,int widthRatio,int heightRatio) throws IOException{

   FileOutputStream out = null;

   try{

   //读入文件  

           File file = new File(srcImagePath);  

           // 构造Image对象  

           BufferedImage src = javax.imageio.ImageIO.read(file);  

           int width = src.getWidth();  

           int height = src.getHeight();  

           // 缩小边长

           BufferedImage tag = new BufferedImage(width / widthRatio, height / heightRatio, BufferedImage.TYPE_INT_RGB);  

           // 绘制 缩小  后的图片

           tag.getGraphics().drawImage(src, 0, 0, width / widthRatio, height / heightRatio, null);  

           out = new FileOutputStream(toImagePath);  

           JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  

           encoder.encode(tag);  

   }catch(Exception e){

   e.printStackTrace();

   }finally{

   if(out != null){

               out.close();  

   }

   }

   }


   /**

    * 长高等比例缩小图片

    * @param srcImagePath 读取图片路径

    * @param toImagePath 写入图片路径

    * @param ratio 缩小比例

    * @throws IOException

    */

   public void reduceImageEqualProportion(String srcImagePath,String toImagePath,int ratio) throws IOException{

   FileOutputStream out = null;

   try{

   //读入文件  

           File file = new File(srcImagePath);  

           // 构造Image对象  

           BufferedImage src = javax.imageio.ImageIO.read(file);  

           int width = src.getWidth();  

           int height = src.getHeight();  

           // 缩小边长

           BufferedImage tag = new BufferedImage(width / ratio, height / ratio, BufferedImage.TYPE_INT_RGB);  

           // 绘制 缩小  后的图片

           tag.getGraphics().drawImage(src, 0, 0, width / ratio, height / ratio, null);  

           out = new FileOutputStream(toImagePath);  

           JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  

           encoder.encode(tag);  

   }catch(Exception e){

   e.printStackTrace();

   }finally{

   if(out != null){

               out.close();  

   }

   }

   }

 

   /**

    * 按倍率放大图片

    * @param srcImagePath 读取图形路径

    * @param toImagePath 写入入行路径

    * @param widthRatio 宽度放大比例

    * @param heightRatio 高度放大比例

    * @throws IOException

    */

   public void enlargementImageByRatio(String srcImagePath,String toImagePath,int widthRatio,int heightRatio) throws IOException{

   FileOutputStream out = null;

   try{

   //读入文件  

           File file = new File(srcImagePath);  

           // 构造Image对象  

           BufferedImage src = javax.imageio.ImageIO.read(file);  

           int width = src.getWidth();  

           int height = src.getHeight();  

           // 放大边长

           BufferedImage tag = new BufferedImage(width * widthRatio, height * heightRatio, BufferedImage.TYPE_INT_RGB);  

           //绘制放大后的图片

           tag.getGraphics().drawImage(src, 0, 0, width * widthRatio, height * heightRatio, null);  

           out = new FileOutputStream(toImagePath);  

           JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  

           encoder.encode(tag);  

   }catch(Exception e){

   e.printStackTrace();

   }finally{

   if(out != null){

               out.close();  

   }

   }

   }


/**

    * 长高等比例放大图片

    * @param srcImagePath 读取图形路径

    * @param toImagePath 写入入行路径

    * @param ratio 放大比例

    * @throws IOException

    */

   public void enlargementImageEqualProportion(String srcImagePath,String toImagePath,int ratio) throws IOException{

   FileOutputStream out = null;

   try{

   //读入文件  

           File file = new File(srcImagePath);  

           // 构造Image对象  

           BufferedImage src = javax.imageio.ImageIO.read(file);  

           int width = src.getWidth();  

           int height = src.getHeight();  

           // 放大边长

           BufferedImage tag = new BufferedImage(width * ratio, height * ratio, BufferedImage.TYPE_INT_RGB);  

           //绘制放大后的图片

           tag.getGraphics().drawImage(src, 0, 0, width * ratio, height * ratio, null);  

           out = new FileOutputStream(toImagePath);  

           JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  

           encoder.encode(tag);  

   }catch(Exception e){

   e.printStackTrace();

   }finally{

   if(out != null){

               out.close();  

   }

   }

   }

 

   /**

    * 重置图形的边长大小

    * @param srcImagePath

    * @param toImagePath

    * @param width

    * @param height

    * @throws IOException

    */

   public void resizeImage(String srcImagePath,String toImagePath,int width,int height) throws IOException{

   FileOutputStream out = null;

   try{

   //读入文件  

           File file = new File(srcImagePath);  

           // 构造Image对象  

           BufferedImage src = javax.imageio.ImageIO.read(file);  

           // 放大边长

           BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  

           //绘制放大后的图片

           tag.getGraphics().drawImage(src, 0, 0, width, height, null);  

           out = new FileOutputStream(toImagePath);  

           JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  

           encoder.encode(tag);  

   }catch(Exception e){

   e.printStackTrace();

   }finally{

   if(out != null){

               out.close();  

   }

   }

   }

 

   /**

    * 横向拼接图片(两张)

    * @param firstSrcImagePath 第一张图片的路径

    * @param secondSrcImagePath 第二张图片的路径

    * @param imageFormat 拼接生成图片的格式

    * @param toPath 拼接生成图片的路径

    */

   public void joinImagesHorizontal(String firstSrcImagePath, String secondSrcImagePath,String imageFormat, String toPath){  

   try {  

   //读取第一张图片    

   File  fileOne  =  new  File(firstSrcImagePath);    

           BufferedImage  imageOne = ImageIO.read(fileOne);    

           int  width  =  imageOne.getWidth();//图片宽度    

           int  height  =  imageOne.getHeight();//图片高度    

           //从图片中读取RGB    

           int[]  imageArrayOne  =  new  int[width*height];    

           imageArrayOne  =  imageOne.getRGB(0,0,width,height,imageArrayOne,0,width);    

       

           //对第二张图片做相同的处理    

           File  fileTwo  =  new  File(secondSrcImagePath);    

           BufferedImage  imageTwo  =  ImageIO.read(fileTwo);

           int width2 = imageTwo.getWidth();

           int height2 = imageTwo.getHeight();

           int[]   ImageArrayTwo  =  new  int[width2*height2];    

           ImageArrayTwo  =  imageTwo.getRGB(0,0,width,height,ImageArrayTwo,0,width);    

           //ImageArrayTwo  =  imageTwo.getRGB(0,0,width2,height2,ImageArrayTwo,0,width2);

       

           //生成新图片

           //int height3 = (height>height2 || height==height2)?height:height2;

           BufferedImage  imageNew  =  new  BufferedImage(width*2,height,BufferedImage.TYPE_INT_RGB);    

           //BufferedImage  imageNew  =  new  BufferedImage(width+width2,height3,BufferedImage.TYPE_INT_RGB);    

           imageNew.setRGB(0,0,width,height,imageArrayOne,0,width);//设置左半部分的RGB  

           imageNew.setRGB(width,0,width,height,ImageArrayTwo,0,width);//设置右半部分的RGB

           //imageNew.setRGB(width,0,width2,height2,ImageArrayTwo,0,width2);//设置右半部分的RGB    

       

           File  outFile  =  new  File(toPath);    

           ImageIO.write(imageNew,  imageFormat,  outFile);//写图片

       } catch (Exception e) {  

       e.printStackTrace();  

       }  

   }

 

   /**

* 横向拼接一组(多张)图像

* @param pics  将要拼接的图像

* @param type 图像写入格式

* @param dst_pic 图像写入路径

* @return

*/

   public  boolean joinImageListHorizontal(String[] pics, String type, String dst_pic) {  

   try {  

   int len = pics.length;  

   if (len < 1) {  

   System.out.println("pics len < 1");  

               return false;  

           }  

   File[] src = new File[len];  

   BufferedImage[] images = new BufferedImage[len];  

   int[][] imageArrays = new int[len][];  

   for (int i = 0; i < len; i++) {  

   src[i] = new File(pics[i]);  

   images[i] = ImageIO.read(src[i]);  

   int width = images[i].getWidth();  

   int height = images[i].getHeight();  

   imageArrays[i] = new int[width * height];// 从图片中读取RGB    

   imageArrays[i] = images[i].getRGB(0, 0, width, height,  imageArrays[i], 0, width);  

   }  

 

   int dst_width = 0;  

   int dst_height = images[0].getHeight();  

   for (int i = 0; i < images.length; i++) {  

   dst_height = dst_height > images[i].getHeight() ? dst_height : images[i].getHeight();  

   dst_width += images[i].getWidth();

   }  

   //System.out.println(dst_width);  

   //System.out.println(dst_height);  

   if (dst_height < 1) {  

   System.out.println("dst_height < 1");  

   return false;  

   }

   /*

   * 生成新图片

   */  

   BufferedImage ImageNew = new BufferedImage(dst_width, dst_height,  BufferedImage.TYPE_INT_RGB);  

   int width_i = 0;

   for (int i = 0; i < images.length; i++) {  

   ImageNew.setRGB(width_i, 0, images[i].getWidth(), dst_height,  imageArrays[i], 0, images[i].getWidth());  

   width_i += images[i].getWidth();

   }  

   File outFile = new File(dst_pic);  

   ImageIO.write(ImageNew, type, outFile);// 写图片  

   } catch (Exception e) {  

           e.printStackTrace();  

           return false;  

       }  

       return true;  

   }

 

   /**

    * 纵向拼接图片(两张)

    * @param firstSrcImagePath 读取的第一张图片

    * @param secondSrcImagePath 读取的第二张图片

    * @param imageFormat 图片写入格式

    * @param toPath 图片写入路径

    */

   public void joinImagesVertical(String firstSrcImagePath, String secondSrcImagePath,String imageFormat, String toPath){  

       try {  

       //读取第一张图片    

           File  fileOne  =  new  File(firstSrcImagePath);    

           BufferedImage  imageOne = ImageIO.read(fileOne);    

           int  width  =  imageOne.getWidth();//图片宽度    

           int  height  =  imageOne.getHeight();//图片高度    

           //从图片中读取RGB    

           int[]  imageArrayOne  =  new  int[width*height];    

           imageArrayOne  =  imageOne.getRGB(0,0,width,height,imageArrayOne,0,width);    

   

           //对第二张图片做相同的处理    

           File  fileTwo  =  new  File(secondSrcImagePath);    

           BufferedImage  imageTwo  =  ImageIO.read(fileTwo);

           int width2 = imageTwo.getWidth();

           int height2 = imageTwo.getHeight();

           int[]   ImageArrayTwo  =  new  int[width2*height2];    

           ImageArrayTwo  =  imageTwo.getRGB(0,0,width,height,ImageArrayTwo,0,width);    

           //ImageArrayTwo  =  imageTwo.getRGB(0,0,width2,height2,ImageArrayTwo,0,width2);  


//生成新图片

           //int width3 = (width>width2 || width==width2)?width:width2;

           BufferedImage  imageNew  =  new  BufferedImage(width,height*2,BufferedImage.TYPE_INT_RGB);    

           //BufferedImage  imageNew  =  new  BufferedImage(width3,height+height2,BufferedImage.TYPE_INT_RGB);    

           imageNew.setRGB(0,0,width,height,imageArrayOne,0,width);//设置上半部分的RGB    

           imageNew.setRGB(0,height,width,height,ImageArrayTwo,0,width);//设置下半部分的RGB

           //imageNew.setRGB(0,height,width2,height2,ImageArrayTwo,0,width2);//设置下半部分的RGB    

   

           File  outFile  =  new  File(toPath);    

           ImageIO.write(imageNew,  imageFormat,  outFile);//写图片

       } catch (Exception e) {  

           e.printStackTrace();  

       }  

   }

 

   /**

    * 纵向拼接一组(多张)图像

    * @param pics 将要拼接的图像数组

    * @param type 写入图像类型

    * @param dst_pic 写入图像路径

    * @return

    */

public  boolean joinImageListVertical(String[] pics, String type, String dst_pic) {  

       try {  

       int len = pics.length;  

           if (len < 1) {  

               System.out.println("pics len < 1");  

               return false;  

           }  

       File[] src = new File[len];  

            BufferedImage[] images = new BufferedImage[len];  

            int[][] imageArrays = new int[len][];  

            for (int i = 0; i < len; i++) {  

           //System.out.println(i);

          src[i] = new File(pics[i]);  

          images[i] = ImageIO.read(src[i]);  

          int width = images[i].getWidth();  

          int height = images[i].getHeight();  

          imageArrays[i] = new int[width * height];// 从图片中读取RGB  

          imageArrays[i] = images[i].getRGB(0, 0, width, height,  imageArrays[i], 0, width);  

      }  

         

      int dst_height = 0;  

      int dst_width = images[0].getWidth();  

      for (int i = 0; i < images.length; i++) {  

          dst_width = dst_width > images[i].getWidth() ? dst_width : images[i].getWidth();  

          dst_height += images[i].getHeight();  

      }  

      //System.out.println(dst_width);  

      //System.out.println(dst_height);  

      if (dst_height < 1) {  

          System.out.println("dst_height < 1");  

          return false;  

      }  

      /*

       * 生成新图片

       */  

           BufferedImage ImageNew = new BufferedImage(dst_width, dst_height,  BufferedImage.TYPE_INT_RGB);  

           int height_i = 0;  

           for (int i = 0; i < images.length; i++) {  

               ImageNew.setRGB(0, height_i, dst_width, images[i].getHeight(),  imageArrays[i], 0, dst_width);  

               height_i += images[i].getHeight();  

           }  

           File outFile = new File(dst_pic);  

           ImageIO.write(ImageNew, type, outFile);// 写图片  

       } catch (Exception e) {  

           e.printStackTrace();  

           return false;  

       }  

       return true;  

   }  

 

   /**

    * 合并图片(按指定初始x、y坐标将附加图片贴到底图之上)

    * @param negativeImagePath 背景图片路径

    * @param additionImagePath 附加图片路径

    * @param x 附加图片的起始点x坐标

    * @param y  附加图片的起始点y坐标

    * @param toPath 图片写入路径

    * @throws IOException

    */

   public void mergeBothImage(String negativeImagePath,String additionImagePath,int x,int y,String toPath ) throws IOException{

   InputStream is= null;

   InputStream is2= null;

   OutputStream os = null;

   try{

   is=new FileInputStream(negativeImagePath);

           is2=new FileInputStream(additionImagePath);

           BufferedImage image=ImageIO.read(is);

           BufferedImage image2=ImageIO.read(is2);

           Graphics g=image.getGraphics();

           g.drawImage(image2,x,y,null);

           os = new FileOutputStream(toPath);

           JPEGImageEncoder enc=JPEGCodec.createJPEGEncoder(os);

           enc.encode(image);

   }catch(Exception e){

   e.printStackTrace();

   }finally{

   if(os != null){

   os.close();

   }

   if(is2 != null){

   is2.close();

   }

   if(is != null){

   is.close();

   }

   }

   }

相关文章
|
13小时前
|
XML 前端开发 Oracle
16:JSP简介、注释与Scriptlet、Page指令元素、Include操作、内置对象、四种属性-Java Web
16:JSP简介、注释与Scriptlet、Page指令元素、Include操作、内置对象、四种属性-Java Web
8 2
|
2天前
|
存储 NoSQL 安全
java 中通过 Lettuce 来操作 Redis
java 中通过 Lettuce 来操作 Redis
java 中通过 Lettuce 来操作 Redis
|
2天前
|
分布式计算 DataWorks Java
DataWorks操作报错合集之在使用MaxCompute的Java SDK创建函数时,出现找不到文件资源的情况,是BUG吗
DataWorks是阿里云提供的一站式大数据开发与治理平台,支持数据集成、数据开发、数据服务、数据质量管理、数据安全管理等全流程数据处理。在使用DataWorks过程中,可能会遇到各种操作报错。以下是一些常见的报错情况及其可能的原因和解决方法。
15 0
|
2天前
|
Java 测试技术 Python
《手把手教你》系列技巧篇(三十六)-java+ selenium自动化测试-单选和多选按钮操作-番外篇(详解教程)
【4月更文挑战第28天】本文简要介绍了自动化测试的实战应用,通过一个在线问卷调查(&lt;https://www.sojump.com/m/2792226.aspx/&gt;)为例,展示了如何遍历并点击问卷中的选项。测试思路包括找到单选和多选按钮的共性以定位元素,然后使用for循环进行点击操作。代码设计方面,提供了Java+Selenium的示例代码,通过WebDriver实现自动答题。运行代码后,可以看到控制台输出和浏览器的相应动作。文章最后做了简单的小结,强调了本次实践是对之前单选多选操作的巩固。
11 0
|
3天前
|
分布式计算 DataWorks 监控
DataWorks操作报错合集之DataWorks在调用java sdk的createFile功能时报错com.aliyuncs.exceptions.ClientException: 1201111000 如何解决
DataWorks是阿里云提供的一站式大数据开发与治理平台,支持数据集成、数据开发、数据服务、数据质量管理、数据安全管理等全流程数据处理。在使用DataWorks过程中,可能会遇到各种操作报错。以下是一些常见的报错情况及其可能的原因和解决方法。
9 1
|
3天前
|
存储 前端开发 测试技术
《手把手教你》系列技巧篇(三十五)-java+ selenium自动化测试-单选和多选按钮操作-下篇(详解教程)
【4月更文挑战第27天】本文介绍了使用Java+Selenium进行Web自动化测试时,如何遍历和操作多选按钮的方法。文章分为两个部分,首先是一个本地HTML页面的示例,展示了多选按钮的HTML代码和页面效果,并详细解释了遍历多选按钮的思路:找到所有多选按钮的共同点,通过定位这些元素并放入list容器中,然后使用for循环遍历并操作。 第二部分介绍了在JQueryUI网站上的实战,给出了被测网址,展示了代码设计,同样使用了findElements()方法获取所有多选按钮并存储到list中,然后遍历并进行点击操作。最后,文章对整个过程进行了小结,并推荐了作者的其他自动化测试教程资源。
11 0
|
5天前
|
前端开发 测试技术 Python
《手把手教你》系列技巧篇(三十三)-java+ selenium自动化测试-单选和多选按钮操作-上篇(详解教程)
【4月更文挑战第25天】本文介绍了自动化测试中如何处理单选和多选按钮的操作,包括它们的定义、HTML代码示例以及如何判断和操作这些元素。文章通过一个简单的HTML页面展示了单选和多选框的示例,并提供了Java+Selenium实现的代码示例,演示了如何检查单选框是否选中以及如何进行全选操作。
11 0
|
7天前
|
Java
【java基础】File操作详解
【java基础】File操作详解
8 0
|
7天前
|
数据采集 前端开发 测试技术
《手把手教你》系列技巧篇(三十一)-java+ selenium自动化测试- Actions的相关操作-番外篇(详解教程)
【4月更文挑战第23天】本文介绍了网页中的滑动验证码的实现原理和自动化测试方法。作者首先提到了网站的反爬虫机制,并表示在本地创建一个没有该机制的网页,然后使用谷歌浏览器进行验证。接着,文章详细讲解了如何使用WebElement的click()方法以及Action类提供的API来模拟鼠标的各种操作,如右击、双击、悬停和拖动。
9 2
|
8天前
|
前端开发 JavaScript Java
java使用jodd操作html
java使用jodd操作html
13 1