import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Base64;
/**
* @author shilei
* @date 2019年6月20日 下午4:53:05
* @desc 图片与Base64转换
*/
@Slf4j
public class ImageBase64Util {
/**
* @param base64 编码字符串
* @param filePath 具体到文件
* @Desc: 将base64编码字符串转换为图片
*/
public static boolean decryptByBase64(String base64, String filePath) {
if (StringUtils.isBlank(base64) || StringUtils.isBlank(filePath))
return false;
try {
Files.write(Paths.get(filePath), Base64.getDecoder().decode(base64), StandardOpenOption.CREATE);
return new File(filePath).exists();
} catch (IOException e) {
log.error(e.getCause().toString());
return false;
}
}
/**
* @Desc: 根据图片地址转换为base64编码字符串
*/
public static String encryptToBase64(String filePath) {
if (StringUtils.isBlank(filePath))
return "生成文件失败,请给出相应的数据";
try {
byte[] b = Files.readAllBytes(Paths.get(filePath));
return Base64.getEncoder().encodeToString(b);
} catch (IOException e) {
log.error(e.getCause().toString());
return null;
}
}
/**
* @Desc: 根据上传的图片转换为base64编码字符串
*/
public static String encryptToBase64(MultipartFile multiFile) {
try {
byte[] b = multiFile.getBytes();
return Base64.getEncoder().encodeToString(b);
} catch (IOException e) {
log.error(e.getCause().toString());
return null;
}
}
}
Base64编码与图片 互转
于 2019-11-22 15:44:16 首次发布