一、生成验证码
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
public class Jsp9v3 {
private static Random random = new Random();
public static final String VERIFY_CODES = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz大江东去波浪接天中华历史岁月五千炎黄共称民族祖先导平水涨违命坐监商代金属文记骨片武王政绩除害分田战国征杀形态纷繁你抢我夺角逐其间也曾退让昨却一箭杰士变法能者富川老子无为道德名典依存互根错或福善仲尼博爱且把学办因材施教贵以精专百家争论各持己见认识深奥影响久远石申守夜修室鲁班指切损益端午追原作品总括钟音十全首脑规定确立集权度量器具字体币钱刑责疑犯乡里受连阿房秀丽长城防线陈胜起义众所企盼打透锅底项带师团四面是歌刘觉志满休养生息提议节减推恩令下调控铁盐兴读易理正统则显新的改制举步维艰增兵卡压绿林好汉奖罚并用消租裁捐两层势力内外藏患轻将头束克了村县派使张某西出阳关网络永留欧亚同欢超遇困境化解危难英走区域行程早晚造纸购料价低简便地动晨晓奇特应验按例讲析九章题算证系组方疗效求散司马虽死重于巨山写赋优美佳话流传球队比赛舞似飞燕随着攻略负在米燃几条计策投降这般亮语左右三足实现谁心尽知气数甚短务必保住它处斯馆风声不停庆功谢安南北朝际登场轮换希望融合期待双眼圆周率值要术汇编花源余香从军木兰湖光入图帮助补点容纳神像范与批判科考择才始自杨坚由广临座绝色独占输送财宝运河承担包围预示星移斗转太宗只闻那些直言强续就职她很果断继瑞景象社会向前街市销售牌号找店松赞干布公主婚联取经之旅越障涉险访日客居古今纪念但听喜讯招致背叛群镇割据朋党竞坛失败阵亡后想稳健车辆刚过赵州路段校对小注倒刻整板夫已目测尚需查看毒性温病医护救援李白格律吸引俄韩伯乐朗笑驴跑腿弹高级技艺当空吴展油彩映画女孩托篮更序频报缺衣少员该府给予巴结胡男龙服加身杯酒得愿青贷均税济世局限激烈警告支付盟款素质较差交手即完突禁唱曲黑发冲冠何须有罪位列最冤买卖微利常靠票券领土扩幅成吉思汗森沙圳津每置巡检式样仍然密织被单另装食类近海航船紧急信件快速进站普货至都份额亿万毕升研究排印活版准备离港配块罗盘火药爆破开采基建介绍授时积极笔谈苦著农书营构庭院针索模型资治通鉴苏门放任清照委婉陆游习否辛又操练问案戏迷幕终伤感明初创业省和相免许诺厂卫抓拿口宣八股答试做父母官哪个惊叫孙儿遭赶培育良种二季丰产机户供费劳工银赚七回别友到非洲边没吃跟顺席末血染设套射击真够威严怎么决意尔等脚软再次亲讨部落谋反上获哈达拉萨执签迎候他们故园来还协约划界收复台湾审核标本环顾察鲜什物悉附春牛荣选状元及第京剧表演红楼伊人云雨雷电热汽播露康宁多年往事录此评述参半诉说情况仅如视管适可而止请您细观大江东去波浪接天中华历史岁月五千炎黄共称民族祖先导平水涨违命坐监商代金属文记骨片武王政绩除害分田战国征杀形态纷繁你抢我夺角逐其间也曾退让昨却一箭杰士变法能者富川老子无为道德名典依存互根错或福善仲尼博爱且把学办因材施教贵以精专百家争论各持己见认识深奥影响久远石申守夜修室鲁班指切损益端午追原作品总括钟音十全首脑规定确立集权度量器具字体币钱刑责疑犯乡里受连阿房秀丽长城防线陈胜起义众所企盼打透锅底项带师团四面是歌刘觉志满休养生息提议节减推恩令下调控铁盐兴读易理正统则显新的改制举步维艰增兵卡压绿林好汉奖罚并用消租裁捐两层势力内外藏患轻将头束克了村县派使张某西出阳关网络永留欧亚同欢超遇困境化解危难英走区域行程早晚造纸购料价低简便地动晨晓奇特应验按例讲析九章题算证系组方疗效求散司马虽死重于巨山写赋优美佳话流传球队比赛舞似飞燕随着攻略负在米燃几条计策投降这般亮语左右三足实现谁心尽知气数甚短务必保住它处斯馆风声不停庆功谢安南北朝际登场轮换希望融合期待双眼圆周率值要术汇编花源余香从军木兰湖光入图帮助补点容纳神像范与批判科考择才始自杨坚由广临座绝色独占输送财宝运河承担包围预示星移斗转太宗只闻那些直言强续就职她很果断继瑞景象社会向前街市销售牌号找店松赞干布公主婚联取经之旅越障涉险访日客居古今纪念但听喜讯招致背叛群镇割据朋党竞坛失败阵亡后想稳健车辆刚过赵州路段校对小注倒刻整板夫已目测尚需查看毒性温病医护救援李白格律吸引俄韩伯乐朗笑驴跑腿弹高级技艺当空吴展油彩映画女孩托篮更序频报缺衣少员该府给予巴结胡男龙服加身杯酒得愿青贷均税济世局限激烈警告支付盟款素质较差交手即完突禁唱曲黑发冲冠何须有罪位列最冤买卖微利常靠票券领土扩幅成吉思汗森沙圳津每置巡检式样仍然密织被单另装食类近海航船紧急信件快速进站普货至都份额亿万毕升研究排印活版准备离港配块罗盘火药爆破开采基建介绍授时积极笔谈苦著农书营构庭院针索模型资治通鉴苏门放任清照委婉陆游习否辛又操练问案戏迷幕终伤感明初创业省和相免许诺厂卫抓拿口宣八股答试做父母官哪个惊叫孙儿遭赶培育良种二季丰产机户供费劳工银赚七回别友到非洲边没吃跟顺席末血染设套射击真够威严怎么决意尔等脚软再次亲讨部落谋反上获哈达拉萨执签迎候他们故园来还协约划界收复台湾审核标本环顾察鲜什物悉附春牛荣选状元及第京剧表演红楼伊人云雨雷电热汽播露康宁多年往事录此评述参半诉说情况仅如视管适可而止请您细观大江东去波浪接天中华历史岁月五千炎黄共称民族祖先导平水涨违命坐监商代金属文记骨片武王政绩除害分田战国征杀形态纷繁你抢我夺角逐其间也曾退让昨却一箭杰士变法能者富川老子无为道德名典依存互根错或福善仲尼博爱且把学办因材施教贵以精专百家争论各持己见认识深奥影响久远石申守夜修室鲁班指切损益端午追原作品总括钟音十全首脑规定确立集权度量器具字体币钱刑责疑犯乡里受连阿房秀丽长城防线陈胜起义众所企盼打透锅底项带师团四面是歌刘觉志满休养生息提议节减推恩令下调控铁盐兴读易理正统则显新的改制举步维艰增兵卡压绿林好汉奖罚并用消租裁捐两层势力内外藏患轻将头束克了村县派使张某西出阳关网络永留欧亚同欢超遇困境化解危难英走区域行程早晚造纸购料价低简便地动晨晓奇特应验按例讲析九章题算证系组方疗效求散司马虽死重于巨山写赋优美佳话流传球队比赛舞似飞燕随着攻略负在米燃几条计策投降这般亮语左右三足实现谁心尽知气数甚短务必保住它处斯馆风声不停庆功谢安南北朝际登场轮换希望融合期待双眼圆周率值要术汇编花源余香从军木兰湖光入图帮助补点容纳神像范与批判科考择才始自杨坚由广临座绝色独占输送财宝运河承担包围预示星移斗转太宗只闻那些直言强续就职她很果断继瑞景象社会向前街市销售牌号找店松赞干布公主婚联取经之旅越障涉险访日客居古今纪念但听喜讯招致背叛群镇割据朋党竞坛失败阵亡后想稳健车辆刚过赵州路段校对小注倒刻整板夫已目测尚需查看毒性温病医护救援李白格律吸引俄韩伯乐朗笑驴跑腿弹高级技艺当空吴展油彩映画女孩托篮更序频报缺衣少员该府给予巴结胡男龙服加身杯酒得愿青贷均税济世局限激烈警告支付盟款素质较差交手即完突禁唱曲黑发冲冠何须有罪位列最冤买卖微利常靠票券领土扩幅成吉思汗森沙圳津每置巡检式样仍然密织被单另装食类近海航船紧急信件快速进站普货至都份额亿万毕升研究排印活版准备离港配块罗盘火药爆破开采基建介绍授时积极笔谈苦著农书营构庭院针索模型资治通鉴苏门放任清照委婉陆游习否辛又操练问案戏迷幕终伤感明初创业省和相免许诺厂卫抓拿口宣八股答试做父母官哪个惊叫孙儿遭赶培育良种二季丰产机户供费劳工银赚七回别友到非洲边没吃跟顺席末血染设套射击真够威严怎么决意尔等脚软再次亲讨部落谋反上获哈达拉萨执签迎候他们故园来还协约划界收复台湾审核标本环顾察鲜什物悉附春牛荣选状元及第京剧表演红楼伊人云雨雷电热汽播露康宁多年往事录此评述参半诉说情况仅如视管适可而止请您细观她很果断继瑞景象社会向前街市销售牌号找店松赞干布公主婚联取经之旅越障涉险访日客居古今纪念但听喜讯招致背叛群镇割据朋党竞坛失败阵亡后想稳健车辆刚过赵州路段校对小注倒刻整板夫已目测尚需查看毒性温病医护救援李白格律吸引俄韩伯乐朗笑驴跑腿弹高级技艺当空吴展油彩映画女孩托篮更序频报缺衣少员该府给予巴结胡男龙服加身杯酒得愿青贷均税济世局限激烈警告支付盟款素质较差交手即完突禁唱曲黑发冲冠何须有罪位列最冤买卖微利常靠票券领土扩幅成吉思汗森沙圳津每置巡检式样仍然密织被单另装食类近海航船紧急信件快速进站普货至都份额亿万毕升研究排印活版准备离港配块罗盘火药爆破开采基建介绍授时积极笔谈苦著农书营构庭院针索模型资治通鉴苏门放任清照委婉陆游习否辛又操练问案戏迷幕终伤感明初创业省和相免许诺厂卫抓拿口宣八股答试做父母官哪个惊叫孙儿遭赶培育良种二季丰产机户供费劳工银赚七回别友到非洲边没吃跟顺席末血染设套射击真够威严怎么决意尔等脚软再次亲讨部落谋反上获哈达拉萨执签迎候他们故园来还协约划界收复台湾审核标本环顾察鲜什物悉附春牛荣选状元及第京剧表演红楼伊人云雨雷电热汽播露康宁多年往事录此评述参半诉说情况仅如视管适可而止请您细观";
private static ImgFontByte imgFontByte = new ImgFontByte();
private static int[] fontStyle = {Font.PLAIN};
private static String generateVerifyCode() {
int codesLen = VERIFY_CODES.length();
Random rand = new Random(System.currentTimeMillis());
StringBuilder verifyCode = new StringBuilder(6);
for (int i = 0; i < 6; i++) {
verifyCode.append(VERIFY_CODES.charAt(rand.nextInt(codesLen - 1)));
}
return verifyCode.toString();
}
public static boolean isChineseChar(char c) {
return String.valueOf(c).matches("[\u4e00-\u9fa5]");
}
/**
* 输出指定验证码图片流
*/
private static void outputImage(int w, int h, String path, String code, Color needColor, StringBuilder needCode) throws IOException {
Color[] fontColor = new Color[]{needColor, needColor, Color.BLUE, Color.YELLOW, Color.RED, Color.GREEN, Color.BLACK};
int verifySize = code.length();
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = image.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Color c = getRandColor();
g2.setColor(c);// 设置边框色
g2.fillRect(0, 0, w, h);
g2.setColor(c);// 设置背景色
g2.fillRect(0, 2, w, h - 4);
char[] charts = code.toCharArray();
for (int i = 0; i < charts.length; i++) {
g2.setColor(getRandColor());// 设置背景色
g2.setFont(getRandomFont(h));
g2.fillRect(0, 2, w, h - 4);
}
g2.setColor(Color.green);// 设置线条的颜色为绿色
int lineNumbers = random.nextInt(4);
for (int i = 0; i < lineNumbers; i++) {
int x = random.nextInt(w - 1);
int y = random.nextInt(h - 1);
int xl = random.nextInt(6) + 1;
int yl = random.nextInt(12) + 1;
g2.drawLine(x, y, x + xl + 40, y + yl + 20);
}
// 2.添加噪点
float yawpRate = 0.05f;
int area = (int) (yawpRate * w * h);
for (int i = 0; i < area; i++) {
int x = random.nextInt(w);
int y = random.nextInt(h);
int rgb = getRandomIntColor();
image.setRGB(x, y, rgb);
}
// 3.使图片扭曲
shear(g2, w, h, c);
char[] chars = code.toCharArray();
// 生成字符
Random random = new Random();
Color defaultFontColor;
int n = random.nextInt(fontColor.length);
defaultFontColor = fontColor[n];
int[] ch = {0, 1, 2, 3, 4, 5};
Set<Integer> set = new HashSet<>();
Random ran = new Random();
while (set.size() < verifySize) {
set.add(ch[ran.nextInt(ch.length)]);
}
Object[] choice = set.toArray();
Arrays.sort(choice);
Random rand = new Random();
int mustId = ran.nextInt(verifySize);
int offset = random.nextInt(20);
for (int i = 0; i < verifySize; i++) {
int id = (int) choice[i];
double rd = rand.nextDouble();
boolean rb = rand.nextBoolean();
Color tempColor;
if (i != mustId) {
tempColor = (Color) randomArray(fontColor);
} else {
tempColor = needColor;
}
Color need = tempColor;
if (needCode != null && need.equals(needColor)) {
needCode.append(chars[i]);
}
g2.setColor(need);
if (isChineseChar(chars[i])){
g2.setFont(new Font("宋体", Font.PLAIN ,getRandomFontSize(h)));
}
else {
g2.setFont(getRandomFont(h));
}
AffineTransform affine = new AffineTransform();
affine.setToRotation(Math.PI / 4 * rd * (rb ? 1 : -1),(w / verifySize) * i + (h - 4) / 2, h / 2);
g2.setTransform(affine);
g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + (h - 4) / 2 - 8);
}
for (int i = 0; i < (random.nextInt(5) + 1); i++) {
Color tempColor;
tempColor = (Color) randomArray(new Color[]{defaultFontColor, Color.GREEN});
g2.setColor(tempColor);
g2.drawLine(random.nextInt(100), random.nextInt(30), random.nextInt(100), random.nextInt(30));
}
g2.dispose();
File dir = new File(path);
File outputFile = new File(dir, (needCode == null ? code : needCode.toString()) + "_" + UUID.randomUUID().toString().replace("-", "").toLowerCase() + ".png");
File parentFile = outputFile.getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs();
}
outputFile.createNewFile();
FileOutputStream fos = new FileOutputStream(outputFile);
ImageIO.write(image, "jpg", fos);
fos.close();
}
private static Object randomArray(Object[] elements) {
Random random = new Random();
int n = random.nextInt(elements.length);
return elements[n];
}
private static Color getRandColor() {
int fc = 150;
int bc = 250;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
private static int getRandomIntColor() {
int[] rgb = getRandomRgb();
int color = 0;
for (int c : rgb) {
color = color << 8;
color = color | c;
}
return color;
}
private static int[] getRandomRgb() {
int[] rgb = new int[3];
for (int i = 0; i < 3; i++) {
rgb[i] = random.nextInt(255);
}
return rgb;
}
/**
* 随机字体、随机风格、随机大小
*/
private static Font getRandomFont(int h) {
// 字体样式
int style = fontStyle[random.nextInt(fontStyle.length)];
// 字体大小
int size = getRandomFontSize(h);
return new ImgFontByte().getFont(size, style);
}
/**
* 获取字体大小按范围随机
*/
private static int getRandomFontSize(int h) {
return h - 16;
}
/**
* 3D中空字体自定义属性类
*/
static class ImgFontByte {
public Font getFont(int fontSize, int fontStyle) {
try {
return new Font("Action Jackson", fontStyle, fontSize);
} catch (Exception e) {
return new Font("Arial", fontStyle, fontSize);
}
}
}
/**
* 字符和干扰线扭曲
*/
private static void shear(Graphics g, int w1, int h1, Color color) {
shearX(g, w1, h1, color);
shearY(g, w1, h1, color);
}
/**
* x轴扭曲
*/
private static void shearX(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(2);
int frames = 1;
int phase = random.nextInt(2);
for (int i = 0; i < h1; i++) {
double d = (double) (period / 2) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
g.copyArea(0, i, w1, 1, (int) d, 0);
g.setColor(color);
g.drawLine((int) d, i, 0, i);
g.drawLine((int) d + w1, i, w1, i);
}
}
/**
* y轴扭曲
*/
private static void shearY(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(40) + 10; // 50;
int frames = 20;
int phase = 7;
for (int i = 0; i < w1; i++) {
double d = (double) (period / 2) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
g.copyArea(i, 0, 1, h1, 0, (int) d);
g.setColor(color);
g.drawLine(i, (int) d, i, 0);
g.drawLine(i, (int) d + h1, i, h1);
}
}
/**
* 本地测试类,可以生成样例验证码图片供观看效果
*/
public static void main(String[] args) throws IOException {
int w = 90, h = 35;
for (int i = 0; i < 100000; i++) {
StringBuilder needCode = new StringBuilder();
String verifyCode = generateVerifyCode();
System.out.println("生成第" + i + "张图片");
outputImage(w, h, "D:/TrainSet/java_captcha_3_Red", verifyCode, Color.RED, needCode);
}
for (int i = 0; i < 10000; i++) {
StringBuilder needCode = new StringBuilder();
String verifyCode = generateVerifyCode();
System.out.println("生成第" + i + "张图片");
outputImage(w, h, "D:/TrainSet/java_captcha_3_Blue", verifyCode, Color.BLUE, needCode);
}
for (int i = 0; i < 10000; i++) {
StringBuilder needCode = new StringBuilder();
String verifyCode = generateVerifyCode();
System.out.println("生成第" + i + "张图片");
outputImage(w, h, "D:/TrainSet/java_captcha_3_Yellow", verifyCode, Color.YELLOW, needCode);
}
for (int i = 0; i < 10000; i++) {
StringBuilder needCode = new StringBuilder();
String verifyCode = generateVerifyCode();
System.out.println("生成第" + i + "张图片");
outputImage(w, h, "D:/TrainSet/java_captcha_3_Green", verifyCode, Color.GREEN, needCode);
}
for (int i = 0; i < 10000; i++) {
StringBuilder needCode = new StringBuilder();
String verifyCode = generateVerifyCode();
System.out.println("生成第" + i + "张图片");
outputImage(w, h, "D:/TrainSet/java_captcha_3_Black", verifyCode, Color.BLACK, needCode);
}
for (int i = 0; i < 10000; i++) {
String verifyCode = generateVerifyCode();
System.out.println("生成第" + i + "张图片");
outputImage(w, h, "D:/TrainSet/java_captcha_3_All", verifyCode, Color.BLACK, null);
}
}
}
参考:https://github.com/kerlomz/captcha_trainer
二、PPT转成MP4
# -*- coding: UTF-8 -*-
import win32com.client
import time
import os
import sys
import shutil
def ppt_to_mp4(ppt_path,mp4_target,resolution = 720,frames = 24,quality = 60,timeout = 120):
# status:Convert result. 0:failed. -1: timeout. 1:success.
status = 0
if ppt_path == '' or mp4_target == '':
return status
# start_tm:Start time
start_tm = time.time()
# Create a folder that does not exist.
sdir = mp4_target[:mp4_target.rfind('\\')]
if not os.path.exists(sdir):
os.makedirs(sdir)
# Start converting
ppt = win32com.client.Dispatch('PowerPoint.Application')
presentation = ppt.Presentations.Open(ppt_path,WithWindow=False)
# CreateVideo() function usage: https://docs.microsoft.com/en-us/office/vba/api/powerpoint.presentation.createvideo
presentation.CreateVideo(mp4_target,-1,1,resolution,frames,quality)
while True:
try:
time.sleep(0.1)
if time.time() - start_tm > timeout:
# Converting time out. Killing the PowerPoint process(An exception will be threw out).
os.system("taskkill /f /im POWERPNT.EXE")
status = -1
break
if os.path.exists(mp4_path) and os.path.getsize(mp4_target) == 0:
# The filesize is 0 bytes when convert do not complete.
continue
status = 1
break
except Exception, e:
print 'Error! Code: {c}, Message, {m}'.format(c = type(e).__name__, m = str(e))
break
print time.time()-start_tm
if status != -1:
ppt.Quit()
return status
if __name__ == '__main__':
# Require Windows system(Media Player was enabled) and Microsoft Office 2010 or higher.
# Converting ppt into video relies on Windows Media Player. So you need to enable Desktop Experience feature.
# More save types please visit: https://docs.microsoft.com/en-us/office/vba/api/powerpoint.ppsaveasfiletype
# quality:0-100. The level of quality of the slide. The higher the number, the higher the quality.
quality = 60
# resolution:The resolution of the slide. 480,720,1080...
resolution = 720
# frames: The number of frames per second.
frames = 24
# ppt_path:The ppt/pptx/pptm file path.
ppt_path = os.path.abspath('./test.pptx')
# mp4_path:The mp4 video save path.
mp4_path = os.path.abspath('./test.mp4')
# ie_temp_dir:The convert cache file path.
# The default path (hidden) is 'C:/Users/username/AppData/Local/Microsoft/Windows/Temporary Internet Files/Content.MSO/ppt'.
# Or 'C:/Users/username/AppData/Local/Microsoft/Windows/INetCache/Content.MSO/ppt'
# You can find the cache folde at IE setting.
# If you don't want clear cache files,assign ie_temp_dir with empty string.
#ie_temp_dir = 'C:/Users/username/AppData/Local/Microsoft/Windows/INetCache/Content.MSO/ppt'
ie_temp_dir = ''
# status:Converting result. 0:failed. -1: timeout. 1:success.
status = 0
# timeout: Seconds that converting time out.
timeout = 4*60
try:
status = ppt_to_mp4(ppt_path,mp4_path,resolution,frames,quality,timeout)
# Clear PowerPoint cache after convert completed. When you converted hundreds of files, the cache folder will be huge.
if ie_temp_dir != '':
shutil.rmtree(ie_temp_dir, ignore_errors=True)
except Exception, e:
print 'Error! Code: {c}, Message, {m}'.format(c = type(e).__name__, m = str(e))
if status == -1:
print 'Failed:timeout.'
elif status == 1:
print 'Success!'
else:
if os.path.exists(mp4_path):
os.remove(mp4_path)
print 'Failed:The ppt may have unknow elements. You can try to convert it manual.'