如何根据1像素高BufferedImage的宽度确定1:1分辨率方形尺寸?
将1px高的线性BufferedImage转换为方形图像的尺寸处理方案
核心思路
当原图像宽度的平方根不是整数时,取平方根的向上取整值作为方形的边长——这是能容纳所有原像素的最小整数边长,剩余空像素直接设为透明即可。
尺寸计算方法
用Math.ceil(Math.sqrt(originalWidth))计算最小整数边长,转换为int类型后就是所需的方形尺寸:
int originalWidth = linearImg.getWidth(); int squareSize = (int) Math.ceil(Math.sqrt(originalWidth));
举个例子:
- 原宽度为10,平方根≈3.16,向上取整为4,4×4的方形可容纳全部10个像素
- 原宽度为7,平方根≈2.64,向上取整为3,3×3的方形可容纳全部7个像素
完整转换实现
结合你现有的编码逻辑,添加一个转换为方形图像的方法:
public static BufferedImage encode(String str){ byte[] bytes = str.getBytes(); BufferedImage img = new BufferedImage(bytes.length, 1, BufferedImage.TYPE_INT_ARGB); for (int i = 0; i < bytes.length; i++) { img.setRGB(i, 0, encode(bytes[i]).getRGB()); } return img; } public static Color encode(byte byt){ return new Color(byt+128, byt+128, byt+128); } // 转换为方形图像的方法 public static BufferedImage convertToSquare(BufferedImage linearImg) { int originalWidth = linearImg.getWidth(); int squareSize = (int) Math.ceil(Math.sqrt(originalWidth)); BufferedImage squareImg = new BufferedImage(squareSize, squareSize, BufferedImage.TYPE_INT_ARGB); int pixelIndex = 0; // 逐行填充像素,超出原长度的位置设为透明 for (int y = 0; y < squareSize; y++) { for (int x = 0; x < squareSize; x++) { if (pixelIndex < originalWidth) { squareImg.setRGB(x, y, linearImg.getRGB(pixelIndex, 0)); pixelIndex++; } else { // 透明像素:ARGB的alpha通道为0 squareImg.setRGB(x, y, 0x00000000); } } } return squareImg; }
使用示例
public static void main(String[] args) { // 生成线性图像 BufferedImage linearImg = encode("Hello StackExchange"); // 转换为方形图像 BufferedImage squareImg = convertToSquare(linearImg); // 后续处理方形图像(如保存、展示) }
内容的提问来源于stack exchange,提问作者John Mayot
相关产品推荐
相关产品推荐

