Java给图片添加边框

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import jxl.Workbook;
import jxl.write.WritableImage;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;


public class AddBorder {
 public static void main(String[] args) {
 new AddBorder().addBorderToImage("e:/test.png");
 }

 public void addBorderToImage(String filePath) {
  try {
   File _file = new File(filePath); // 读入文件
   Image src = javax.imageio.ImageIO.read(_file); // 构造Image对象
   int width = src.getWidth(null); // 得到源图宽
   int height = src.getHeight(null); // 得到源图长

   BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
   Graphics graphics = image.getGraphics();
   graphics.drawImage(src, 0, 0, width, height, null); // 绘制图
   // 画边框

   graphics.setColor(Color.BLACK);
   graphics.drawRect(0, 0, width - 1, height - 1);
   graphics.drawRect(1, 1, width - 1, height - 1);
   graphics.drawRect(0, 0, width-2, height- 2); 

   FileOutputStream out = new FileOutputStream(filePath); // 输出到文件流
   JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
   encoder.encode(image);
   out.close();
  }
  catch (IOException e) {
   e.printStackTrace();
  }
 }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Java的ImageIO类和BufferedImage类来给图片边框并输出为PNG格式的图片。以下是一个示例代码: ```java import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; public class ImageBorderAdder { public static void main(String[] args) throws Exception { // 读取原始图片 BufferedImage inputImage = ImageIO.read(new File("input.png")); int inputWidth = inputImage.getWidth(); int inputHeight = inputImage.getHeight(); // 创建带边框的新图片 int borderSize = 10; int outputWidth = inputWidth + 2 * borderSize; int outputHeight = inputHeight + 2 * borderSize; BufferedImage outputImage = new BufferedImage(outputWidth, outputHeight, BufferedImage.TYPE_INT_ARGB); // 绘制边框 Graphics2D graphics = outputImage.createGraphics(); graphics.setColor(Color.BLACK); graphics.fillRect(0, 0, outputWidth, outputHeight); graphics.drawImage(inputImage, borderSize, borderSize, null); graphics.dispose(); // 输出新图片 ImageIO.write(outputImage, "png", new File("output.png")); } } ``` 在上面的代码中,我们首先读取了一张名为"input.png"的原始图片,然后创建了一张带有10像素黑色边框的新图片,并将原始图片绘制在边框内部。最后,我们将新图片输出为"output.png"文件。 需要注意的是,本代码中的边框颜色为黑色,如果需要更改为其他颜色,只需要将代码中的`Color.BLACK`替换为相应的颜色即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值