java 创建新的图片,底色自己设定

本文介绍了一种在图片下方添加描述的方法,并实现了图片与描述的合成。具体步骤包括:创建空白图片、添加描述文字,最后将图片与描述合成一张完整的图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我的需求是:在照片下方加上照片描述.

思路:

1,先创建与照片宽度一样的白底图片,

2,在图片上写上对应照片的描述.

3.创建的白底图片与照片合成一张图片

一:创建图片

package tuPian;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
 
public class DrawPic {
	
	public static void main(String[] args) throws IOException {
        //照片的路径
		String bigImg = "C:\\Users\\sclf\\Desktop\\开发临时文档\\任务状态\\正在开发\\新建文件夹\\";
		File SJfile = new File(bigImg);
		File[] listFiles = SJfile.listFiles();
	//绘图.
		for (File ffile : listFiles) {
			int width = getImgWidth(ffile);//获取照片的宽度
			int height = 60;//描述的高度自己定义
			String substring = ffile.toString().substring(bigImg.length());
			/*
			 * 正则表达式获取图片的名字.
			 * 	当然你的名字如果不是  中文名+.jpg 用我这个正则表达式 是不生效的.需要你自己处理你的名字
			 * 
			 */
					String re = "[r'-?/.jpg']";
					String name = substring.replaceAll(re, "");
					
			//设置图片的高度与宽度.
			BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
			//创建出来的图片存储的路径
			final File file = new File("C:\\Users\\sclf\\Desktop\\开发临时文档\\任务状态\\正在开发\\描述图片\\"+name+".jpg");
			
			if(file.exists()) {
				file.delete();
				file.createNewFile();
			}
			writeImage(bi, "jpg", file,width,height);
		}
 
		System.out.println("绘图成功");
	
	    
	    
		
	}
	
	/** 通过指定参数写一个图片  */
    public static boolean writeImage(BufferedImage bi, String picType, File file,int width,int height) {
   
    	Graphics g = bi.createGraphics();
//设置底片的颜色
    	Color color = new Color(255,255,255);
        g.setColor(color);
//底片的宽高为多少.如果不写宽高你的图片创建出来是黑色的
        g.fillRect(0, 0, width, height);
        g.dispose();
        bi.flush();
        boolean val = false;
        try {
            val = ImageIO.write(bi, picType, file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return val;
    }
    /**
     * 获取图片宽度
     * @param file  图片文件
     * @return 宽度
     */
    public static int getImgWidth(File file) {
        InputStream is = null;
        BufferedImage src = null;
        int ret = -1;
        try {
            is = new FileInputStream(file);
            src = javax.imageio.ImageIO.read(is);
            ret = src.getWidth(null); // 得到源图宽
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

}

二:图片上写文字/或者 图片上插入图片

package tuPian;

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

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.ParseException;

public class aa2 {
	public static void main(String[] args) throws ParseException {
		try {
			String content = null;
			String outPath = null;
			String bigImg = "C:\\Users\\sclf\\Desktop\\开发临时文档\\任务状态\\正在开发\\描述图片\\";
			File SJfile = new File(bigImg);
			File[] listFiles = SJfile.listFiles();
			for (File file : listFiles) {
				System.out.println(file);
				int imgWidth = getImgWidth(file);
				int imgHeight =45; //图片的高度.我给固定死了,你们随意变 
				String substring = file.toString().substring(bigImg.length());
				String re = "[r'-?/.jpg']";
				String name = substring.replaceAll(re, "");
				//图片上需要写的内容
				content = "院士肖像来源于国家出版基金项目 院士风采-中国工程院院士数字影像集";
				//图片需要保存的位置
				outPath = "C:\\Users\\sclf\\Desktop\\开发临时文档\\任务状态\\正在开发\\完整的描述\\" + name + ".jpg";
				
				/*
				 * 第一个参数:String类型的图片路径
				 * 第二个参数:在图片上插入的图片--------------不用本功能传null就行
				 * 第三个参数:你要在图片上插入图片的 x 坐标(x,y)
				 * 第四个参数:你要在图片上插入图片的 y 坐标(x,y)
				 * 第五个参数:在图片上插入文本内容--------------不用本功能传null就行
				 * 第六个参数:你要在图片上插入图片的 x 坐标(x,y)
				 * 第七个参数:你要在图片上插入图片的 y 坐标(x,y)
				 * 第八个参数:需要把图片保存的路径
				 */
					
				bigImgAddSmallImgAndText(file.toString(), null, 222, 222, content, imgWidth / 12, imgHeight, outPath);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/***
	 * 在一张大图张添加小图和文字
	 * 
	 * @param bigImgPath
	 *            大图的路径
	 * @param smallImgPath
	 *            小图的路径
	 * @param sx
	 *            小图在大图上x抽位置
	 * @param sy
	 *            小图在大图上y抽位置
	 * @param content
	 *            文字内容
	 * @param cx
	 *            文字在大图上y抽位置
	 * @param cy
	 *            文字在大图上y抽位置
	 * @param outPathWithFileName
	 *            结果输出路径
	 */
	public static void bigImgAddSmallImgAndText(String bigImgPath, String smallImgPath, int sx, int sy, String content,
			int cx, int cy, String outPathWithFileName) throws IOException {
		// 主图片的路径
		InputStream is = new FileInputStream(bigImgPath);
		// 通过JPEG图象流创建JPEG数据流解码器
		JPEGImageDecoder jpegDecoder = JPEGCodec.createJPEGDecoder(is);
		// 解码当前JPEG数据流,返回BufferedImage对象
		BufferedImage buffImg = jpegDecoder.decodeAsBufferedImage();
		// 得到画笔对象
		Graphics g = buffImg.getGraphics();

		// 小图片的路径
		if (smallImgPath != null) {
			ImageIcon imgIcon = new ImageIcon(smallImgPath);
			// 得到Image对象。
			Image img = imgIcon.getImage();
			// 将小图片绘到大图片上,5,300 .表示你的小图片在大图片上的位置。
			g.drawImage(img, sx, sy, null);

			// 设置颜色。
			g.setColor(Color.WHITE);
		}
//				院士肖像来源于国家出版基金项目 院士风采-中国工程院院士数字影像集
		// 最后一个参数用来设置字体的大小
		if (content != null) {
				Font f = new Font("微软雅黑", Font.PLAIN, 24);
			Color mycolor = Color.black;
			g.setColor(mycolor);
			g.setFont(f);
			g.drawString(content, cx, cy); // 表示这段文字在图片上的位置(cx,cy) .第一个是你设置的内容。
		}
		g.dispose();
		OutputStream os = new FileOutputStream(outPathWithFileName);
		// 创键编码器,用于编码内存中的图象数据。
		JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(os);
		en.encode(buffImg);
		is.close();
		os.close();
	}
	/**
     * 获取图片宽度
     * @param file  图片文件
     * @return 宽度
     */
    public static int getImgWidth(File file) {
        InputStream is = null;
        BufferedImage src = null;
        int ret = -1;
        try {
            is = new FileInputStream(file);
            src = javax.imageio.ImageIO.read(is);
            ret = src.getWidth(null); // 得到源图宽
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }
    /**
     * 获取图片宽度
     * @param file  图片文件
     * @return 高度
     */
    public static int getImgHeight(File file) {
        InputStream is = null;
        BufferedImage src = null;
        int ret = -1;
        try {
            is = new FileInputStream(file);
            src = javax.imageio.ImageIO.read(is);
            ret = src.getHeight();// 得到源图宽
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

}

三:图片合成

点击下边连接.已经写过一片图片合成的文章.参考以下连接

https://mp.youkuaiyun.com/postedit/88949769

### 使用Java获取图片主色或背景色的方法 在Java中,可以通过多种方式实现图片主色或背景色的提取。以下方法基于常见的图像处理库和算法实现。 #### 1. 使用Java内置工具 通过Java的`BufferedImage`类可以读取图片像素信息,并计算出图片的主色或背景色。具体实现步骤包括加载图片、遍历像素值以及统计颜色频率。 ```java import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; public class ImageColorExtractor { public static Color getDominantColor(BufferedImage image) { int[] colorCount = new int[16777216]; // RGB范围 for (int x = 0; x < image.getWidth(); x++) { for (int y = 0; y < image.getHeight(); y++) { int rgb = image.getRGB(x, y); if (rgb != -1) { // 忽略透明像素 colorCount[rgb]++; } } } int dominantIndex = 0; int maxCount = 0; for (int i = 0; i < colorCount.length; i++) { if (colorCount[i] > maxCount) { maxCount = colorCount[i]; dominantIndex = i; } } return new Color(dominantIndex); } public static void main(String[] args) throws Exception { BufferedImage image = ImageIO.read(new File("path/to/image.png")); Color dominantColor = getDominantColor(image); System.out.println("Dominant Color: " + dominantColor.getRed() + ", " + dominantColor.getGreen() + ", " + dominantColor.getBlue()); } } ``` 上述代码通过遍历图片的所有像素点并统计每种颜色出现的次数来确定主色[^4]。 #### 2. 使用第三方库(如Leptonica) 如果需要更复杂的颜色提取功能,可以借助第三方库。例如,引用[2]提到的Leptonica库能够进行颜色量化,从而提取图片的主题色。以下是使用Leptonica的基本思路: - 加载图片。 - 调用Leptonica的颜色量化函数。 - 获取量化后的颜色列表。 虽然Leptonica本身是一个C语言库,但可以通过JNI或其他绑定技术在Java中调用其功能[^5]。 #### 3. 使用Android Jetpack Palette(适用于Android环境) 如果目标平台是Android,可以直接使用Jetpack中的`Palette`类来提取图片的颜色信息。例如,引用[1]提到的`getDominantColor`方法可以快速获取图片的主色调。以下是一个示例代码片段: ```java import android.graphics.Bitmap; import android.graphics.Color; import androidx.palette.graphics.Palette; public class AndroidColorExtractor { public static int getDominantColor(Bitmap bitmap) { Palette palette = Palette.from(bitmap).generate(); Palette.Swatch vibrantSwatch = palette.getDominantSwatch(); return vibrantSwatch != null ? vibrantSwatch.getRgb() : Color.TRANSPARENT; } } ``` 此方法简单高效,但在非Android环境中不可用[^6]。 #### 4. 颜色聚类算法 对于更复杂的场景,可以采用颜色聚类算法(如K-Means)来提取图片的主色或背景色。以下是基本流程: - 将图片转换为像素矩阵。 - 对像素矩阵应用K-Means聚类。 - 统计每个聚类中心的颜色频率,选择频率最高的作为主色。 以下是基于Java的伪代码示例: ```java import org.apache.commons.math3.ml.clustering.KMeansPlusPlusClusterer; import org.apache.commons.math3.ml.clustering.Cluster; import org.apache.commons.math3.ml.distance.EuclideanDistance; public class KMeansColorExtractor { public static Color getDominantColor(BufferedImage image, int clusterCount) { List<double[]> pixels = new ArrayList<>(); for (int x = 0; x < image.getWidth(); x++) { for (int y = 0; y < image.getHeight(); y++) { Color color = new Color(image.getRGB(x, y)); pixels.add(new double[]{color.getRed(), color.getGreen(), color.getBlue()}); } } KMeansPlusPlusClusterer<double[]> clusterer = new KMeansPlusPlusClusterer<>(clusterCount, 10, new EuclideanDistance()); List<Cluster<double[]>> clusters = clusterer.cluster(pixels); // 找到最大的簇 Cluster<double[]> largestCluster = Collections.max(clusters, Comparator.comparing(cluster -> cluster.getPoints().size())); double[] centroid = largestCluster.getCenter().getPoint(); return new Color((int) centroid[0], (int) centroid[1], (int) centroid[2]); } } ``` 此方法依赖Apache Commons Math库,适合处理大型图片数据集[^7]。 ### 总结 根据实际需求选择合适的方法: - 简单场景下,使用`BufferedImage`直接统计像素颜色即可。 - 如果需要更高性能或更复杂的功能,可以考虑使用第三方库或颜色聚类算法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值