Compare commits

...

3 Commits

Author SHA1 Message Date
l52863727
605aa74845 封装了黑白图片上色,风格转换和人像动漫化的百度api 2024-11-03 23:06:03 +08:00
l52863727
da9af1fc2c 封装了黑白图片上色,风格转换和人像动漫化的百度api 2024-10-29 22:26:53 +08:00
l52863727
048a1c2b90 Changes 2024-10-28 15:54:52 +08:00
38 changed files with 239226 additions and 865 deletions

View File

@ -11,10 +11,14 @@
<module name="backend" /> <module name="backend" />
</profile> </profile>
</annotationProcessing> </annotationProcessing>
<bytecodeTargetLevel>
<module name="master" target="1.6" />
</bytecodeTargetLevel>
</component> </component>
<component name="JavacSettings"> <component name="JavacSettings">
<option name="ADDITIONAL_OPTIONS_OVERRIDE"> <option name="ADDITIONAL_OPTIONS_OVERRIDE">
<module name="backend" options="-parameters" /> <module name="backend" options="-parameters" />
<module name="master" options="-parameters" />
<module name="sms-backend" options="-parameters" /> <module name="sms-backend" options="-parameters" />
</option> </option>
</component> </component>

124
.idea/uiDesigner.xml Normal file
View File

@ -0,0 +1,124 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Palette2">
<group name="Swing">
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.svg" removable="false" auto-create-binding="false" can-attach-label="true">
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values>
<property name="text" value="Button" />
</initial-values>
</item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="RadioButton" />
</initial-values>
</item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="CheckBox" />
</initial-values>
</item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values>
<property name="text" value="Label" />
</initial-values>
</item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" />
</default-constraints>
</item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
</group>
</component>
</project>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

File diff suppressed because one or more lines are too long

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 MiB

File diff suppressed because one or more lines are too long

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

File diff suppressed because one or more lines are too long

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

File diff suppressed because one or more lines are too long

Binary file not shown.

Binary file not shown.

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

26
pom.xml
View File

@ -119,6 +119,11 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId> <artifactId>spring-boot-starter-undertow</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
@ -129,11 +134,20 @@
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId> <artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional> <optional>true</optional>
</dependency> </dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>
<!--lombok用来简化实体类--> <!--lombok用来简化实体类-->
<dependency> <dependency>
<groupId>org.projectlombok</groupId> <groupId>org.projectlombok</groupId>
@ -283,6 +297,18 @@
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -0,0 +1,49 @@
package com.message.Baidu_ai_API.Enum;
public enum PicStyle {
CARTOON(1, "cartoon"),
PENCIL(2, "pencil"),
COLOR_PENCIL(3, "color_pencil"),
WARM(4, "warm"),
WAVE(5, "wave"),
LAVENDER(6, "lavender"),
MONONOKE(7, "mononoke"),
SCREAM(8, "scream"),
GOTHIC(9, "gothic");
private final int styleCode;
private final String styleName;
PicStyle(int styleCode, String styleName) {
this.styleCode = styleCode;
this.styleName = styleName;
}
public int getStyleCode() {
return styleCode;
}
public String getStyleName() {
return styleName;
}
// 从整数获取枚举值
public static PicStyle fromStyleCode(int styleCode) {
for (PicStyle style : values()) {
if (style.getStyleCode() == styleCode) {
return style;
}
}
throw new IllegalArgumentException("Invalid style code: " + styleCode);
}
// 从字符串获取枚举值
public static PicStyle fromStyleName(String styleName) {
for (PicStyle style : values()) {
if (style.getStyleName().equalsIgnoreCase(styleName)) {
return style;
}
}
throw new IllegalArgumentException("Invalid style name: " + styleName);
}
}

View File

@ -1,4 +1,4 @@
package com.Baidu_ai_API.config; package com.message.Baidu_ai_API.config;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;

View File

@ -0,0 +1,93 @@
package com.message.Baidu_ai_API.controller;
import com.message.Baidu_ai_API.config.ExternalResourceConfig;
import com.message.Baidu_ai_API.service.AiPictureService;
import com.message.Baidu_ai_API.util.FileSetUtil;
import com.base.annotation.SysLog;
import com.base.helper.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
@Api(tags = "百度ai调用")
@RestController
@RequestMapping("/AiPicture")
public class AiPictureController {
@Value("${external.resource.dir}")
private String externalResourceDir;
@Autowired
private AiPictureService aiPictureService;
@Autowired
private ExternalResourceConfig externalResourceConfig;
@SysLog(action = "AiPicture:Colourize", value = "ai图像增强黑白图片上色")
@ApiOperation(value = "黑白图片上色",notes = "ai图像增强")
@RequestMapping(value="Colourize",method = {RequestMethod.POST})
@ApiImplicitParams({
@ApiImplicitParam(name = "userid", value = "id", paramType = "query"),//用户id用于生成base64的txt文件用以转储
@ApiImplicitParam(name = "image", value = "图片文件必须是图片才行pngjpg皆可后缀名不限", paramType = "query")})
public ResponseEntity<FileSystemResource> Colourize(@RequestParam("userid")Integer id, @RequestParam("image") MultipartFile image) throws Exception {
String fileName= FileSetUtil.resetFileName(id,externalResourceDir,image);//生成的filename无后缀
File file=FileSetUtil.saveFile(image,externalResourceDir,fileName);//生成的file为png文件
String filePath=aiPictureService.Colourize(fileName,externalResourceDir);//转码传输到baiduapi后写入fileName+.txt,所返回的filePath直接指向对应txt文件
aiPictureService.Base64ToImage(fileName,filePath,externalResourceDir);
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName());
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(new FileSystemResource(file));
}
@SysLog(action = "AiPicture:styleTrans", value = "ai图像增强更换图片风格")
@ApiOperation(value = "更换图片风格",notes = "ai图像增强")
@RequestMapping(value="styleTrans",method = {RequestMethod.POST})
@ApiImplicitParams({
@ApiImplicitParam(name = "userid", value = "id", paramType = "query"),//用户id用于生成base64的txt文件用以转储
@ApiImplicitParam(name = "image", value = "图片文件必须是图片才行pngjpg皆可后缀名不限", paramType = "query"),
@ApiImplicitParam(name = "options", value = "图片转换的风格,1:卡通画,2:铅笔风格,3:彩色铅笔画,4:彩色糖块油画,5:神奈川冲浪里油画,6:薰衣草油画,7:奇异油画,8:呐喊油画,9:哥特油画。", paramType = "query")})
public ResponseEntity<FileSystemResource> styleTrans(@RequestParam("userid")Integer id, @RequestParam("image") MultipartFile image, @RequestParam("options") Integer options) throws Exception {
String fileName= FileSetUtil.resetFileName(id,externalResourceDir,image);//生成的filename无后缀
File file=FileSetUtil.saveFile(image,externalResourceDir,fileName);//生成的file为png文件
System.out.println(fileName+"//////////"+externalResourceDir);
String filePath=aiPictureService.styleTrans(fileName,externalResourceDir,options);//转码传输到baiduapi后写入fileName+.txt,所返回的filePath直接指向对应txt文件
aiPictureService.Base64ToImage(fileName,filePath,externalResourceDir);
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName());
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(new FileSystemResource(file));
}
@SysLog(action = "AiPicture:selfie_anime", value = "ai图像增强人像动漫化")
@ApiOperation(value = "人像动漫化",notes = "ai图像增强")
@RequestMapping(value="selfie_anime",method = {RequestMethod.POST})
@ApiImplicitParams({
@ApiImplicitParam(name = "userid", value = "id", paramType = "query"),//用户id用于生成base64的txt文件用以转储
@ApiImplicitParam(name = "image", value = "图片文件必须是图片才行pngjpg皆可后缀名不限", paramType = "query")})
public ResponseEntity<FileSystemResource> selfie_anime(@RequestParam("userid")Integer id, @RequestParam("image") MultipartFile image) throws Exception {
String fileName= FileSetUtil.resetFileName(id,externalResourceDir,image);//生成的filename无后缀
File file=FileSetUtil.saveFile(image,externalResourceDir,fileName);//生成的file为png文件
System.out.println(fileName+"//////////"+externalResourceDir);
String filePath=aiPictureService.selfie_anime(fileName,externalResourceDir);//转码传输到baiduapi后写入fileName+.txt,所返回的filePath直接指向对应txt文件
aiPictureService.Base64ToImage(fileName,filePath,externalResourceDir);
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName());
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(new FileSystemResource(file));
}
}

View File

@ -0,0 +1,11 @@
package com.message.Baidu_ai_API.service;
public interface AiPictureService {
String Colourize(String fileName,String externalResourceDir) throws Exception;
String styleTrans(String fileName,String externalResourceDir,Integer option) throws Exception;
//图片转base64传给baiduapi解析后获取传回来的base64码,图像风格转换
String selfie_anime(String fileName, String externalResourceDir) throws Exception;
void Base64ToImage(String fileName, String txtfilePath, String filePath);
}

View File

@ -0,0 +1,135 @@
package com.message.Baidu_ai_API.service.impl;
import com.message.Baidu_ai_API.Enum.PicStyle;
import com.message.Baidu_ai_API.service.AiPictureService;
import com.message.Baidu_ai_API.util.Base64Util;
import com.message.Baidu_ai_API.util.FileUtil;
import com.message.Baidu_ai_API.util.HttpUtil;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
@Service
public class AiPictureServiceImpl implements AiPictureService {
@Override//图片转base64传给baiduapi解析后获取传回来的base64码,黑白图片上色
public String Colourize(String fileName,String externalResourceDir) throws Exception {//转码传输到baiduapi
// 请求url
String url = "https://aip.baidubce.com/rest/2.0/image-process/v1/colourize";
System.out.println(fileName);
// 本地文件路径
String filePath =externalResourceDir+"\\"+fileName+".png";
byte[] imgData = FileUtil.readFileByBytes(filePath);
String imgStr = Base64Util.encode(imgData);
String imgParam = URLEncoder.encode(imgStr, "UTF-8");
String param = "image=" + imgParam;
String accessToken = "24.97b658223d82fe59e4fa81196a39800c.2592000.1732771197.282335-115915927";
String result = HttpUtil.post(url, accessToken, param);
// 解析JSON并提取image属性
JSONObject jsonObject = new JSONObject(result);
String file = jsonObject.getString("image");
// 将image属性写入文件
String outputFilePath =externalResourceDir+"\\"+fileName+".txt";
try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File(outputFilePath)))) {
writer.write(file);
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println( "写入" + outputFilePath);
return outputFilePath;
}
@Override//图片转base64传给baiduapi解析后获取传回来的base64码,图像风格转换
public String styleTrans(String fileName,String externalResourceDir,Integer option) throws Exception {//转码传输到baiduapi
// 请求url
String url = "https://aip.baidubce.com/rest/2.0/image-process/v1/style_trans";
// 本地文件路径
String filePath =externalResourceDir+"\\"+fileName+".png";
byte[] imgData = FileUtil.readFileByBytes(filePath);
String imgStr = Base64Util.encode(imgData);
String imgParam = URLEncoder.encode(imgStr, "UTF-8");
String StyleName=PicStyle.fromStyleCode(option).getStyleName();//从枚举类获取风格名字选项名字
System.out.println(StyleName);
String param = "option=" + StyleName +"&image=" + imgParam;
String accessToken = "24.1ff0e598cf27db3bcfec07b0e4fb3b38.2592000.1731833877.282335-115915927";
String result = HttpUtil.post(url, accessToken, param);
System.out.println(result);
// 解析JSON并提取image属性
JSONObject jsonObject = new JSONObject(result);
String image = jsonObject.getString("image");
// 将image属性写入文件
String outputFilePath =externalResourceDir+"\\"+fileName+".txt";
try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File(outputFilePath)))) {
writer.write(image);
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println( "写入" + outputFilePath);
return outputFilePath;
}
@Override//图片转base64传给baiduapi解析后获取传回来的base64码,图像风格转换
public String selfie_anime(String fileName,String externalResourceDir) throws Exception {//转码传输到baiduapi
// 请求url
String url = "https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime";
// 本地文件路径
String filePath =externalResourceDir+"\\"+fileName+".png";
byte[] imgData = FileUtil.readFileByBytes(filePath);
String imgStr = Base64Util.encode(imgData);
String imgParam = URLEncoder.encode(imgStr, "UTF-8");
String param ="image=" + imgParam;
String accessToken = "24.1ff0e598cf27db3bcfec07b0e4fb3b38.2592000.1731833877.282335-115915927";
String result = HttpUtil.post(url, accessToken, param);
System.out.println(result);
// 解析JSON并提取image属性
JSONObject jsonObject = new JSONObject(result);
String image = jsonObject.getString("image");
// 将image属性写入文件
String outputFilePath =externalResourceDir+"\\"+fileName+".txt";
try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File(outputFilePath)))) {
writer.write(image);
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println( "写入" + outputFilePath);
return outputFilePath;
}
@Override//将转存好的base64码转为图片
public void Base64ToImage(String fileName,String txtfilePath,String filePath){
// 输入 Base64 编码文件的路径
String outputImagePath =filePath+"\\"+fileName+".png";
try (BufferedReader reader = Files.newBufferedReader(Paths.get(txtfilePath))) {
StringBuilder base64StringBuilder = new StringBuilder();
char[] buffer = new char[1024]; // 用于读取文件的缓冲区
int bytesRead;
// 按块读取 Base64 编码文件
while ((bytesRead = reader.read(buffer)) != -1) {
base64StringBuilder.append(buffer, 0, bytesRead);
}
String base64String = base64StringBuilder.toString();
try {
byte[] imageBytes = Base64.getDecoder().decode(base64String);
try (FileOutputStream fos = new FileOutputStream(outputImagePath)) {
fos.write(imageBytes);
System.out.println("图像已成功保存到 " + outputImagePath);
}
} catch (IllegalArgumentException e) {
System.err.println("解码失败,可能是因为数据不完整或格式错误: " + e.getMessage());
}
}
catch (IOException e) {
e.printStackTrace();
System.err.println("读取或写入文件时出错: " + e.getMessage());
}
}
}

View File

@ -1,4 +1,4 @@
package com.Baidu_ai_API.util; package com.message.Baidu_ai_API.util;
/** /**
* Base64 工具类 * Base64 工具类

View File

@ -0,0 +1,59 @@
package com.message.Baidu_ai_API.util;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.Random;
public class FileSetUtil {
public static String resetFileName(final Integer id,String path,MultipartFile image) throws IOException {
System.out.println(path);
// 生成新的文件名
long timestamp = System.currentTimeMillis();
Random random = new Random();
int randomNumber = random.nextInt(1000); // 生成一个 0 999 之间的随机数
// 构建新的文件名
String newFileName = id + "_" + timestamp + "_" + randomNumber;
File newFile = new File(path, newFileName+".png");
try (InputStream is = image.getInputStream();
FileOutputStream fos = new FileOutputStream(newFile)) {
byte[] buffer = new byte[1024];
int bytesRead;
// 从源文件读取并写入目标文件
while ((bytesRead = is.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
System.out.println("文件保存成功: " + newFile.getAbsolutePath());
return newFileName;
} catch (IOException e) {
throw new IOException("文件保存失败: " + e.getMessage(), e);
}
}
public static File saveFile(MultipartFile file, String path, String fileName) {
File newFile = new File(path, fileName+".png");
File parentDir = newFile.getParentFile();
if (parentDir != null && !parentDir.exists()) {
parentDir.mkdirs(); // 创建所有必要的父目录
}
try (InputStream is = file.getInputStream();
FileOutputStream fos = new FileOutputStream(newFile)) {
byte[] buffer = new byte[1024];
int bytesRead;
// 从源文件读取并写入目标文件
while ((bytesRead = is.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
return newFile;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -1,4 +1,4 @@
package com.Baidu_ai_API.util; package com.message.Baidu_ai_API.util;
import java.io.*; import java.io.*;

View File

@ -1,5 +1,5 @@
package com.Baidu_ai_API.util; package com.message.Baidu_ai_API.util;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;

View File

@ -1,4 +1,4 @@
package com.Baidu_ai_API.util; package com.message.Baidu_ai_API.util;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.DataOutputStream; import java.io.DataOutputStream;

View File

@ -57,7 +57,7 @@ userproperties:
logging.level.com.hejr.springboot2_003.mapper: debug logging.level.com.hejr.springboot2_003.mapper: debug
external: external:
resource: resource:
dir: ../external-resources dir: D:/学习/dc试验/master/external-resources
#单点登录信息 #单点登录信息
sso: sso:
appId: 500000099 appId: 500000099

View File

@ -0,0 +1,33 @@
{
"groups": [
{
"name": "external",
"type": "com.message.Baidu_ai_API.config.ExternalResourceConfig",
"sourceType": "com.message.Baidu_ai_API.config.ExternalResourceConfig"
},
{
"name": "spring.datasource",
"type": "javax.sql.DataSource",
"sourceType": "com.message.config.DataSourceConfig",
"sourceMethod": "druid()"
},
{
"name": "userproperties",
"type": "com.message.config.UserConfig",
"sourceType": "com.message.config.UserConfig"
}
],
"properties": [
{
"name": "external.resource-dir",
"type": "java.lang.String",
"sourceType": "com.message.Baidu_ai_API.config.ExternalResourceConfig"
},
{
"name": "userproperties.updatepwdtime",
"type": "java.lang.Long",
"sourceType": "com.message.config.UserConfig"
}
],
"hints": []
}

View File

@ -57,7 +57,7 @@ userproperties:
logging.level.com.hejr.springboot2_003.mapper: debug logging.level.com.hejr.springboot2_003.mapper: debug
external: external:
resource: resource:
dir: /path/to/your/external-resources dir: D:/学习/dc试验/master/external-resources
#单点登录信息 #单点登录信息
sso: sso:
appId: 500000099 appId: 500000099