java绘制心形爱心
绘制java心形的核心就是实现:
1.直角坐标系参数方程1
x(t)=a*(2cost-cos(2t))
y(t)=a*(2sint-sin(2t))
2.直角坐标系参数方程2
x = 16*(sin(t))^3 ;
y = 13 * cos(t) - 5 * cos(2t) - 2 * cos(3t) - cos(4t);
上代码:可以直接复制使用
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
* java绘制心形爱心
*/
public class Heart2 {
public static void main(String[] args) {
heart();
heart2();
}
public static void heart(){
//创建一个新的空白BufferedImage对象,800*800
BufferedImage bufferedImage = new BufferedImage(800, 800, BufferedImage.TYPE_INT_ARGB);
//获取图形绘画工具
Graphics2D g2d = bufferedImage.createGraphics();
// 设置颜色和画笔粗细
g2d.setColor(Color.PINK);
g2d.setStroke(new BasicStroke(3.0f));
// 在旋转前先绘制文字【在心形镂空处写上文字】,设置文字大小
Font font = new Font(null, Font.BOLD, 24);
g2d.setFont(font);
g2d.drawString("我爱xxx!",350,400);
g2d.setColor(Color.RED);//重置画笔颜色
// 为了防止生成的心形是倒着放的,创建一个旋转矩阵并旋转180度
AffineTransform at = new AffineTransform();
at.rotate(Math.toRadians(180), 400, 400); // 以图片中心为旋转中心旋转180度
// 将 Graphics2D 上下文变换为旋转后的上下文
g2d.setTransform(at);
// 定义变量
double t = 0;
double x, y;
// 使用方程绘制心形
while (t <= 2 * Math.PI) {
x = 16 *Math.pow(Math.sin(t),3) ;
y = 13 * Math.cos(t) - 5 * Math.cos(2 * t) - 2 * Math.cos(3 * t) - Math.cos(4 * t);
//下面这两行将心形放大十倍
x*=10;
y*=10;
g2d.drawLine((int)x + 400, (int)y + 400, (int)x + 400, (int)y + 400);
t += 0.01;
}
g2d.setColor(Color.BLACK);
// 释放此图形的上下文以及它使用的所有系统资源
g2d.dispose();
// 将图片保存到文件系统中
try {
File outputfile = new File("D:\\heart.png");
outputfile.mkdirs();//如果目录有多级,防止父级目录没有创建,我这里放的是D盘根目录
ImageIO.write(bufferedImage, "png", outputfile);
System.out.println(outputfile.getAbsolutePath()+":绘制成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void heart2(){
// 创建一个新的空白BufferedImage对象
BufferedImage bufferedImage = new BufferedImage(800, 800, BufferedImage.TYPE_INT_ARGB);
//获取图形绘画工具
Graphics2D g2d = bufferedImage.createGraphics();
// 设置颜色和画笔粗细
g2d.setColor(Color.RED);
g2d.setStroke(new BasicStroke(3.0f));
// 为了防止生成的心形是倒着放的,创建一个旋转矩阵并旋转90度
AffineTransform at = new AffineTransform();
at.rotate(Math.toRadians(90), 400, 400); // 以图片中心为旋转中心旋转90度
// 将 Graphics2D 上下文变换为旋转后的上下文
g2d.setTransform(at);
// 定义变量
double t = 0;
double x, y;
// 使用方程绘制心形
while (t <= 2 * Math.PI) {
x = Math.cos(2*t)-2*Math.cos(t) ;
y = Math.sin(2*t)-2*Math.sin(t) ;
//下面这两行将心形放大75倍
x*=75;
y*=75;
g2d.drawLine((int)x + 400, (int)y + 400, (int)x + 400, (int)y + 400);
t += 0.01;
}
// 释放此图形的上下文以及它使用的所有系统资源
g2d.dispose();
// 将图片保存到文件系统中
try {
File outputfile = new File("D:\\heart2.png");
outputfile.mkdirs();//如果目录有多级,防止父级目录没有创建,我这里放的是D盘根目录
ImageIO.write(bufferedImage, "png", outputfile);
System.out.println(outputfile.getAbsolutePath()+":绘制成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
生成效果
heart() 展示效果
heart2() 展示效果
到这里就生成结束了。
下面实现另一个需求:
需求描述
1.编写程序生成一个心形图片
2.上传到服务器,返回图片路径
3.编写程序生成一个二维码,将第二步返回的图片路径写入二维码的文本路径中
要生成二维码,就要引入依赖:
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.1</version>
</dependency>
上代码
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class QRCodeGenerator {
public static void main(String[] args) {
//这里填写第二步返回的图片路径,也可以是自定义的普通文本
//我这里就先填写刘亦菲的图片地址了
String text = "https://www.douban.com/personage/27255495/photo/2364795372/";
//String text ="hello ,二维码!"
int width = 300;
int height = 300;
String format = "png";
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
try {
QRCodeWriter writer = new QRCodeWriter();
BitMatrix bitMatrix = writer.encode(text, BarcodeFormat.QR_CODE, width, height, hints);
File qrFile = new File("D:\\MyQRCode.png");
//生成粉色的
MatrixToImageConfig config=new MatrixToImageConfig(Color.pink.getRGB(),MatrixToImageConfig.WHITE);
MatrixToImageWriter.writeToPath(bitMatrix, format, qrFile.toPath(),config);
//MatrixToImageWriter.toBufferedImage(bitMatrix,config);//可以使用这种方式转成一个BufferedImage,然后就可以使用ImageIO了
} catch (WriterException | IOException e) {
e.printStackTrace();
}
}
}
效果:这个就是包含刘亦菲图片的粉色二维码了
最后附上QRCodeUtil工具类
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
public class QRCodeUtil {
/**
* 编码
*
* @param content
* @param QRcodeWidth
* @param QRcodeHeigh
* @return
* @throws Exception
*/
public static String encodeQR(String content, int QRcodeWidth, int QRcodeHeigh) throws Exception {
QRCodeWriter writer = new QRCodeWriter();
//编码格式
BarcodeFormat barcodeFormat = BarcodeFormat.QR_CODE;
//定义Map集合封装二维码配置信息
Map<EncodeHintType, Object> hints = new HashMap<>();
//设置二维码图片的内容编码
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
// 设置二维码图片的上、下、左、右间隙
hints.put(EncodeHintType.MARGIN, 1);
// 设置二维码的纠错级别
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
BitMatrix bitMatrix = writer.encode(content, barcodeFormat, QRcodeWidth, QRcodeHeigh, hints);
// 设置位矩阵转图片的参数
MatrixToImageConfig config = new MatrixToImageConfig(Color.black.getRGB(), Color.white.getRGB());
BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix, config);
String qrcodeName = "D:\\qrcode.png";
ImageIO.write(image, "png", new File(qrcodeName));
return qrcodeName;
}
/**
* 解码
* @param obj
* @return
* @throws Exception
*/
public static String decodeQR(Object obj) throws Exception {
BufferedImage image =null;
if(obj instanceof File){
File file= (File)obj;
image = ImageIO.read(file);
}
if(obj instanceof URL){
URL url= (URL)obj;
image = ImageIO.read(url);
}
if(obj instanceof String){
String url= (String)obj;
image = ImageIO.read(new URL(url));
}
if(obj instanceof InputStream){
InputStream ins= (InputStream)obj;
image = ImageIO.read(ins);
}
if (image == null) {
return null;
}
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
Hashtable hints = new Hashtable();
hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
QRCodeReader reader = new QRCodeReader();
result = reader.decode(bitmap, hints);
String resultStr = result.getText();
return resultStr;
}