public void createPicTwo2(int x,int y)
{
try
{
//读取第一张图片
File fileOne = new File("h:\\h.jpg");
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("h:\\img.png");
BufferedImage ImageTwo = ImageIO.read(fileTwo);
int widthTwo = ImageTwo.getWidth();//图片宽度
int heightTwo = ImageTwo.getHeight();//图片高度
int[] ImageArrayTwo = new int[widthTwo*heightTwo];
ImageArrayTwo = ImageTwo.getRGB(0,0,widthTwo,heightTwo,ImageArrayTwo,0,widthTwo);
//生成新图片
BufferedImage ImageNew = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
ImageNew.setRGB(0,0,width,height,ImageArrayOne,0,width);//设置左半部分的RGB
ImageNew.setRGB(x,y,widthTwo,heightTwo,ImageArrayTwo,0,widthTwo);//设置右半部分的RGB
ImageNew.setRGB(x*2,y,widthTwo,heightTwo,ImageArrayTwo,0,widthTwo);//设置右半部分的RGB
File outFile = new File("h:\\out.png");
ImageIO.write(ImageNew, "png", outFile);//写图片
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args) {
ImageDraw he = new ImageDraw();
he.createPicTwo2(100, 0);
}
{
try
{
//读取第一张图片
File fileOne = new File("h:\\h.jpg");
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("h:\\img.png");
BufferedImage ImageTwo = ImageIO.read(fileTwo);
int widthTwo = ImageTwo.getWidth();//图片宽度
int heightTwo = ImageTwo.getHeight();//图片高度
int[] ImageArrayTwo = new int[widthTwo*heightTwo];
ImageArrayTwo = ImageTwo.getRGB(0,0,widthTwo,heightTwo,ImageArrayTwo,0,widthTwo);
//生成新图片
BufferedImage ImageNew = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
ImageNew.setRGB(0,0,width,height,ImageArrayOne,0,width);//设置左半部分的RGB
ImageNew.setRGB(x,y,widthTwo,heightTwo,ImageArrayTwo,0,widthTwo);//设置右半部分的RGB
ImageNew.setRGB(x*2,y,widthTwo,heightTwo,ImageArrayTwo,0,widthTwo);//设置右半部分的RGB
File outFile = new File("h:\\out.png");
ImageIO.write(ImageNew, "png", outFile);//写图片
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args) {
ImageDraw he = new ImageDraw();
he.createPicTwo2(100, 0);
}
// 个人代码实例
/**
* 实物商品分享赚 - 分享商品图片(规则最低价格)
*
* @param goodId
* @param groupId
* @param memberId
* @return
*/
@ApiOperation(value = "新增前关键字查重", notes = "新增前关键字查重", httpMethod = "POST")
@ApiImplicitParams({
@ApiImplicitParam(name = "goodId", value = "商品Id", required = true, dataType = "Long", paramType = "query", example = ""),
@ApiImplicitParam(name = "groupId", value = "商户编号", required = true, dataType = "Long", paramType = "query", example = ""),
@ApiImplicitParam(name = "memberId", value = "会员id", required = true, dataType = "Long", paramType = "query", example = "")
})
@ApiResponses(value = {
@ApiResponse(code = 200, message = "成功")
}
)
@RequestMapping(value = "wxsharegoodpicture")
@ResponseBody
@SysLogger(value = "wxsharegoodpicture", servicename = "shop-service")
public ShareMallEntityGood wxsharegoodpicture(@RequestParam(required = true) Long goodId,
@RequestParam(required = true) Long groupId,
@RequestParam(required = true) Long memberId) throws Exception {
logger.info("分享赚-分享商品信息图片");
if (goodId == null) {
throw new ApplicationException(Rescode.NULL_POINTER, "goodId 商品不能为空!");
}
if (groupId == null) {
throw new ApplicationException(Rescode.NULL_POINTER, "groupId 不能为空!");
}
if (memberId == null) {
throw new ApplicationException(Rescode.NULL_POINTER, "memberId 不能为空!");
}
ShareMallEntityGood shareMallEntityGood = new ShareMallEntityGood();
String fileName = null;
byte[] data = new byte[1024];
BASE64Encoder encoder = null;
BufferedOutputStream bos = null;
BufferedImage image;
try {
int imageWidth = 750; //图片的宽度
int imageHeight = 1350; //图片的高度
int H_title = 300; //头部高度
int H_activity = 430; //活动高度
int H_mainPic = 750; //广告高度
int H_tip = 300; //商品价格栏
int tip_2_top = (H_title + H_mainPic);
MallEntityGood mallEntityGood = mallEntityGoodService.queryFindEntityGoodPictureDetail(goodId, groupId);
image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
//设置图片的背景色
Graphics2D main = image.createGraphics();
main.setColor(Color.white);
main.fillRect(0, 0, imageWidth, imageHeight);
//***********************页面头部
Graphics title = image.createGraphics();
title.setColor(Color.BLACK);
// 商品标题字体
Font titleFont = new Font("微软雅黑", Font.PLAIN, 46);
title.setFont(titleFont);
// 如果商品名大于12个字符,截取12个字符在第一行中显示,剩余的在第二行显示
// 完成之后优化 考虑用户在使用英文的前提下 每行字数乘两倍
if (mallEntityGood.getName().length() > 14) {
String goodName1 = URLCodeUtil.encodeParam(mallEntityGood.getName().substring(0, 14));
if (mallEntityGood.getName().length() > 14 && mallEntityGood.getName().length() < 27) {
String goodName2 = URLCodeUtil.encodeParam(mallEntityGood.getName().substring(14));
title.drawString(goodName2, 20, (H_title) / 3 + 80);
} else if (mallEntityGood.getName().length() > 27) {
String goodName2 = URLCodeUtil.encodeParam(mallEntityGood.getName().substring(14, 27));
title.drawString(goodName2 + "...", 20, (H_title) / 3 + 80);
}
title.drawString(goodName1, 20, (H_title) / 3 + 5);
} else {
title.drawString(URLCodeUtil.encodeParam(mallEntityGood.getName()), 20, (H_title) / 3 + 5);
}
// 获取商品所参加的活动
Graphics activity = image.createGraphics();
activity.setColor(Color.red);
Font activityFont = new Font("微软雅黑", Font.PLAIN, 34);
activity.setFont(activityFont);
// 普通动态活动
List<ActivityUnroutine> activityUnroutineList = activityUnroutineService.queryActivityListById(goodId);
// 拼团活动(根据用户等级判断是否享有拼团价拼团活动)
ActivityBulk activityBulk = activityBulkService.queeryActivityBulkByGoodInfo(goodId, groupId);
// 价格处理
DecimalFormat df = new DecimalFormat("0.00");
// 时间处理
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
if (activityBulk != null) {
Member member = memberService.selectByPrimaryKey(memberId);
// 用户等级Id
Long gradeId = member.getGradeId();
if (activityBulk.getUserGradeList().equals("-1")) {
// 用户等级列表 其全部会员等级为-1时 皆可以参与分享拼图活动 分享图文拼图
String activityName = activityBulk.getActivityName();// 拼团活动名称
Date endTime = activityBulk.getEndTime(); // 拼图活动结束时间
ActivityBulkGoodDetail activityBulkGoodDetail = activityBulkGoodDetailService.queryGoodInfo(activityBulk.getId(), goodId);
Long amount = activityBulkGoodDetail.getAmount(); // 拼团价
// 商品存在拼图活动的话 拼团活动优先 (拼团活动名排布)
ptMethod(H_activity, H_tip, tip_2_top, activity, df, format, activityName, endTime, amount,image);
} else if (activityBulk.getUserGradeList().contains(String.valueOf(gradeId))) {
String activityName = activityBulk.getActivityName();// 拼团活动名称
Date endTime = activityBulk.getEndTime(); // 拼图活动结束时间
ActivityBulkGoodDetail activityBulkGoodDetail = activityBulkGoodDetailService.queryGoodInfo(activityBulk.getId(), goodId);
Long amount = activityBulkGoodDetail.getAmount(); // 拼团价
ptMethod(H_activity, H_tip, tip_2_top, activity, df, format, activityName, endTime, amount,image);
}
} else {
// 商品没有参与拼团活动 那么查询时候有参与普通的动态活动
if (activityUnroutineList != null) {
for (int i = 0; i < activityUnroutineList.size(); i++) {
if (StringUtils.isNotEmpty(activityUnroutineList.get(i).getActivityName())) {
String activityNames = activityUnroutineList.get(i).getActivityName();
if (activityNames.length() > 20) {
activity.drawString("活动:" + URLDecoder.decode(activityNames, "UTF-8").substring(0, 21) + "...", 20, (H_activity) / 2 + 30);
} else {
activity.drawString("活动:" + URLDecoder.decode(activityNames, "UTF-8"), 20, (H_activity) / 2 + 30);
}
break;
}
}
} else {
String activityName = "";
activity.drawString(activityName, 20, (H_activity) / 2);
}
// 会员价排布
Graphics2D tip = image.createGraphics();
tip.setColor(Color.red);
Font tipFont = new Font("微软雅黑", Font.PLAIN, 56);
tip.setFont(tipFont);
// 查询该商品时候含有规格--若有去规格的最小价格显示
List<MallEntityGoodSpec> mallEntityGoodSpecs = mallEntityGoodSpecService.selectByGoodId(goodId);
if (mallEntityGoodSpecs.size() != 0) {
List<Integer> pirceList = new ArrayList<>();
for (MallEntityGoodSpec mallEntityGoodSpec : mallEntityGoodSpecs) {
// 取出所有规格的会员价冒泡排序
pirceList.add(mallEntityGoodSpec.getPrice());
}
int temp = 0;
for (int j = 0; j < pirceList.size(); j++) {
int minprice = pirceList.get(0);
Integer pirce = pirceList.get(j);
if (pirce < minprice) {
temp = minprice;
minprice = pirce;
pirce = temp;
}
tip.drawString("¥" + df.format((float) minprice / 100), 250, tip_2_top + (H_tip) / 2 - 40);
}
} else {
tip.drawString("¥" + df.format((float) mallEntityGood.getPromotionPrice() / 100), 250, tip_2_top + (H_tip) / 2 - 40);
}
// 会员分享图片插入
Graphics mainPic3 = image.getGraphics();
BufferedImage bimg3 = null;
String imgurl3 = "http://ebank007.oss-cn-hangzhou.aliyuncs.com/background/20180802190802Zoa43H.jpg";
// String imgurl3="http://ebank007.oss-cn-hangzhou.aliyuncs.com/20180731173813D9PJ9Q.jpg";
bimg3 = ImageIO.read(new URL(imgurl3).openStream());
int width = bimg3.getWidth();
int height = bimg3.getHeight();
// 图片距离随价格长度的增加而增加(价格长度每增加1+图片x轴位移+25)
int priceLength = df.format(mallEntityGood.getPromotionPrice() / 100).length();
int priceSize = 3;
int pictureWidth = 380;
int clength = (priceLength - priceSize) * 31;
int addPictureWidth = pictureWidth + clength;
mainPic3.drawImage(bimg3, addPictureWidth, tip_2_top + (H_tip) / 2 - 85, width, height - 5, null);
mainPic3.dispose();
}
//***********************插入中间广告图
Graphics mainPic = image.getGraphics();
BufferedImage bimg = null;
// 获取商品图片
if (mallEntityGood.getPicture() != null) {
String[] picture = mallEntityGood.getPicture().trim().split(",");
for (int i = 0; i < picture.length; i++) {
if (picture[i].trim().length() > 0) {
bimg = ImageIO.read(new URL(picture[i]).openStream());
mainPic.drawImage(bimg, 0, H_title, imageWidth, H_mainPic, null);
mainPic.dispose();
break;
}
}
}
// 原价排布
Font btnFont2 = new Font("微软雅黑", Font.PLAIN, 30);
Graphics2D btn2 = image.createGraphics();
btn2.setColor(Color.black);
btn2.setFont(btnFont2);
String salePrice = "原价";
btn2.drawString(URLDecoder.decode(salePrice, "UTF-8") + ": ¥" + df.format(mallEntityGood.getSalePrice() / 100), 250, tip_2_top + (H_tip) / 2 + 20);
int proLength = df.format(mallEntityGood.getSalePrice() / 100).length();
int proSize = 3;
String logSign = "----------";
String str = "";
for (int i = 0; i < proLength - proSize; i++) {
str += "--";
}
btn2.drawString(logSign + str, 250, tip_2_top + (H_tip) / 2 + 20);
// 确定二维码所在的位置
Graphics2D tip1 = image.createGraphics();
tip1.setColor(Color.black);
Font tipFont2 = new Font("微软雅黑", Font.PLAIN, 28);
tip1.setFont(tipFont2);
String ccLog = "长按识别二维码";
tip1.drawString("[" + URLDecoder.decode(ccLog, "UTF-8") + "]", 20, tip_2_top + (H_tip) / 2 + 130);
// 用户分享链接二维码
String shareGoodQRcode = HOME_URL + "/api/oAuth2/goodDetailShare?gid=" + goodId + "&" + "memberid=" + memberId + "&" + "groupId=" + groupId;
int qrcode_height = 210;
int qrcode_width = 210;
BufferedImage imageQR = createImage1(shareGoodQRcode, qrcode_width, qrcode_height,image);
// 确定二维码在图中的位置
Graphics mainPic1 = image.getGraphics();
if (image != null) {
// 二维码插入图片
mainPic1.drawImage(imageQR, 20, tip_2_top + 30, qrcode_width, qrcode_height, null);
mainPic1.dispose();
}
// 开始二维码图片与主图合成
//QR
int widthQR = imageQR.getWidth();
int heightQR = imageQR.getHeight();
int[] ImageArrayQR = new int[widthQR * heightQR];
ImageArrayQR = imageQR.getRGB(0,0,widthQR,heightQR,ImageArrayQR,0,widthQR);
//ZT
int widthZT = image.getWidth();
int heightZT = image.getHeight();
int[] ImageArrayZT = new int[widthZT*heightZT];
ImageArrayZT =image.getRGB(0,0,widthZT,heightZT,ImageArrayZT,0,widthZT);
//生成新图片
BufferedImage ImageNew = new BufferedImage(widthZT,heightZT,BufferedImage.TYPE_INT_RGB);
ImageNew.setRGB(20,1080,widthQR,heightQR,ImageArrayQR,0,widthQR);//设置左半部分的RGB
ImageNew.setRGB(0,0,widthZT,heightZT,ImageArrayZT,0,widthZT);//设置右半部分的RGB
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
String code = format.format(new Date()) + "-" + uuid;
fileName =code + ".png";
createImage(fileName,ImageNew);
InputStream in = null;
data = null;
//读取图片字节数组
try {
in = new FileInputStream(fileName);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
//对字节数组Base64编码
encoder = new BASE64Encoder();
if (StringUtils.isNotEmpty(encoder.encode(data))) {
shareMallEntityGood.setPictureEncode(encoder.encode(data));
shareMallEntityGood.setShareGoodQRcode(HOME_URL + "/api/oAuth2/goodDetailShare?gid=" + goodId + "&" + "memberid=" + memberId + "&" + "groupId=" + groupId);
shareMallEntityGood.setErrorCode(Rescode.SUCCESS);
shareMallEntityGood.setErrorMsg("图片生成成功");
} else {
shareMallEntityGood.setErrorCode(Rescode.FAIL);
shareMallEntityGood.setErrorMsg("操作失败");
}
} catch (Exception e) {
e.printStackTrace();
throw new Exception("处理异常");
} finally {
// 删除内存中的图片
// File file = new File(uuid + ".png");
delectFile(fileName);
File f = new File(fileName);
f.delete();
System.out.println("+_____________________________________++");
System.out.println(new File(fileName).exists());
fileOn(fileName);
}
return shareMallEntityGood;
}
private void ptMethod(int h_activity, int h_tip, int tip_2_top, Graphics activity, DecimalFormat df, SimpleDateFormat format, String activityName, Date endTime, Long amount, BufferedImage image) throws IOException {
// 拼团活动名排布
if (StringUtils.isNotEmpty(activityName)) {
if (activityName.length() > 20) {
activity.drawString("活动:" + URLDecoder.decode(activityName, "UTF-8").substring(0, 21) + "...", 20, (h_activity) / 2 + 30);
} else {
activity.drawString("活动:" + URLDecoder.decode(activityName, "UTF-8"), 22, (h_activity) / 2 + 30);
}
}
// 拼团价排布
Graphics2D amountPice = image.createGraphics();
amountPice.setColor(Color.red);
Font amountFont = new Font("微软雅黑", Font.PLAIN, 56);
amountPice.setFont(amountFont);
amountPice.drawString("¥" + df.format(amount / 100), 250, tip_2_top + (h_tip) / 2 - 40);
// 拼团专享图片的插入
Graphics mainPic3 = image.getGraphics();
BufferedImage bimg3;
// 拼团价图片
String imgurl3 = "http://ebank007.oss-cn-hangzhou.aliyuncs.com/merchant/201808081327585pL1lD.jpg";
bimg3 = ImageIO.read(new URL(imgurl3).openStream());
int width = bimg3.getWidth();
int height = bimg3.getHeight();
// 图片距离随价格长度的增加而增加(价格长度每增加1+图片x轴位移+25)
int priceLength = df.format(amount / 100).length();
int priceSize = 3;
int pictureWidth = 380;
int clength = (priceLength - priceSize) * 31;
int addPictureWidth = pictureWidth + clength;
mainPic3.drawImage(bimg3, addPictureWidth, tip_2_top + (h_tip) / 2 - 85, width, height - 5, null);
mainPic3.dispose();
// 排布测试
/* Calendar calendar = Calendar.getInstance();
calendar.setTime(endTime);
calendar.add(Calendar.DAY_OF_MONTH, +1);//+1今天的时间加一天
endTime = calendar.getTime();*/
String time = format.format(endTime);
Graphics2D pb = image.createGraphics();
pb.setColor(Color.red);
Font pbFont = new Font("微软雅黑", Font.PLAIN, 24);
pb.setFont(pbFont);
String activityEndTime = "活动截止日期 : " + time + " (含当天) ";
pb.drawString(URLDecoder.decode(activityEndTime, "UTF-8"), 250, tip_2_top + (h_tip) / 2 + 70);
}
/**
* 二维码图片的生成
*
* @param content 链接
* @param qrcode_width 二维码宽
* @param qrcode_height 二维码高
* @return
* @throws Exception
*/
public static BufferedImage createImage1(String content, int qrcode_width, int qrcode_height ,BufferedImage image) throws Exception {
Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, qrcode_width, qrcode_height, hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
BufferedImage image2 = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image2.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000
: 0xFFFFFFFF);
}
}
return image2;
}
//生成图片文件
@SuppressWarnings("restriction")
public void createImage(String fileLocation, BufferedImage image) {
BufferedOutputStream bos = null;
if (image != null) {
try {
FileOutputStream fos = new FileOutputStream(fileLocation);
bos = new BufferedOutputStream(fos);
// JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
// encoder.encode(image);
ImageIO.write(image, "png", bos);
bos.flush();
image.flush();
fos.close();
bos.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {//关闭输出流
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
/**
* 对文件进行删除操作
*
* @param str 文件路径
*/
public static void delectFile(String str) {
File f = new File(str);
f.delete();
}
/**
* 判断文件是否存在
*
* @param x 文件中路径
*/
public static void fileOn(String x) {
File f = new File(x);
if (f.exists()) {
System.out.println("文件" + f.toString() + "还存在!!!!!!!!");
} else {
System.out.println("文件" + f.toString() + "已删除!!!!!!!!");
}
}
/**
* 当前时间+多少天
*/
public static Date getNextDay(Date date, int sum) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, +sum);//+1今天的时间加一天
date = calendar.getTime();
return date;
}