栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

图片转二进制下载预览

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

图片转二进制下载预览


@Data
@TableName(“user_icon”)
@ApiModel(value=“UserIcon对象”, description=“用户图标”)
public class UserIcon implements Serializable {

private static final long serialVersionUID = 1L;

@ApiModelProperty(value = “编号”)
@TableId(value = “id”, type = IdType.AUTO)
private Long id;

@ApiModelProperty(value = “学号”)
@TableField(“account”)
private String account;

@ApiModelProperty(value = “图标”)
@TableField(“icon”)
private byte[] icon;

@ApiModelProperty(value = “图标”)
@TableField(value = “icon_str”,exist = false)
private String iconStr;

}
banner:
images:
path: /data/images
downicon: /data/downicon
@Value("${banner.images.downicon:}")
private String logoSaveDownicon;


@GetMapping("/getUserIcon/{xh}")
@ApiOperation(value = “根据学号获取用户图标”)
@ApiImplicitParams({
@ApiImplicitParam(name = “xh”, value = “学号”, dataType = “String”)
})
public R getUserIcon(@PathVariable(“xh”) String xh, HttpServletResponse response){
UserIcon userIcon = userIconService.getByAccount(xh);
byte[] value = null;
if(null!=userIcon && null!=userIcon.getIcon()){
value = userIcon.getIcon();
}
byte[] image2byte = image2byte(“F:testimaimagestest.jpg”);
System.out.println(image2byte);
userIcon.setIcon(image2byte);
userIconService.updateById(userIcon);
String images = RandomUtil.uuid();
try {
ByteArrayInputStream bais = new ByteArrayInputStream(userIcon.getIcon());
BufferedImage bi1 = ImageIO.read(bais);
File w2 = new File(“F:testimaimages”+File.separator+images+".jpg");//可以是jpg,png,gif格式
ImageIO.write(bi1, “jpg”, w2);//不管输出什么格式图片,此处不需改动
} catch (IOException e) {
e.printStackTrace();
}
FileUtil.downloadIcon(“F:testimaimages”, images+".jpg", response);
return R.ok().put(“data”, value);
}


@GetMapping("/getUserIcons/{xh}")
@ApiOperation(value = “根据学号获取用户图标”)
@ApiImplicitParams({
@ApiImplicitParam(name = “xh”, value = “学号”, dataType = “String”)
})
public void getUserIcons(@PathVariable(“xh”) String xh, HttpServletResponse response) throws Exception {
UserIcon userIcon = userIconService.getByAccount(xh);
if(null!=userIcon && null!=userIcon.getIcon()){
String images = RandomUtil.uuid();
try {
ByteArrayInputStream bais = new ByteArrayInputStream(userIcon.getIcon());
BufferedImage bi1 = ImageIO.read(bais);
File w2 = new File(“F:testimaimages”+File.separator+images+".jpg");//可以是jpg,png,gif格式
ImageIO.write(bi1, “jpg”, w2);//不管输出什么格式图片,此处不需改动
} catch (IOException e) {
e.printStackTrace();
}
FileUtil.downloadIcon(“F:testimaimages”, images+".jpg", response);
FileUtil.deleteImage(“F:testimaimages”,images+".jpg");
}
}


@GetMapping("/getUserIconss/{xh}")
@ApiOperation(value = “根据学号获取用户图标”)
@ApiImplicitParams({
@ApiImplicitParam(name = “xh”, value = “学号”, dataType = “String”)
})
public void getUserIconss(@PathVariable(“xh”) String xh, HttpServletResponse response) throws Exception {
UserIcon userIcon = userIconService.getByAccount(xh);
if(null!=userIcon && null!=userIcon.getIcon()){
String images = RandomUtil.uuid();
try {
String byte2hex = TestImageBinary.byte2hex(userIcon.getIcon());
base64Decoder decoder=new base64Decoder();
byte[] bytes1 = decoder.decodeBuffer(byte2hex);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
BufferedImage bi1 = ImageIO.read(bais);
File w2 = new File(“F:testimaimages”+File.separator+images+".jpg");//可以是jpg,png,gif格式
ImageIO.write(bi1, “jpg”, w2);//不管输出什么格式图片,此处不需改动
} catch (IOException e) {
e.printStackTrace();
}
FileUtil.downloadIcon(“F:testimaimages”, images+".jpg", response);
FileUtil.deleteImage(“F:testimaimages”,images+".jpg");
}
}


@GetMapping("/getUserIconsss/{xh}")
@ApiOperation(value = “根据学号获取用户图标”)
@ApiImplicitParams({
@ApiImplicitParam(name = “xh”, value = “学号”, dataType = “String”)
})
public void getUserIconsss(@PathVariable(“xh”) String xh, HttpServletResponse response) throws Exception {
UserIcon userIcon = userIconService.getByAccount(xh);
if(null!=userIcon && null!=userIcon.getIconStr()){
String images = RandomUtil.uuid();
try {
base64Decoder decoder=new base64Decoder();
byte[] bytes1 = decoder.decodeBuffer(userIcon.getIconStr());
ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
BufferedImage bi1 = ImageIO.read(bais);
File w2 = new File(“F:testimaimages”+File.separator+images+".jpg");//可以是jpg,png,gif格式
ImageIO.write(bi1, “jpg”, w2);//不管输出什么格式图片,此处不需改动
} catch (IOException e) {
e.printStackTrace();
}
FileUtil.downloadIcon(“F:testimaimages”, images+".jpg", response);
FileUtil.deleteImage(“F:testimaimages”,images+".jpg");
}
}


@GetMapping("/getUserIconssss/{xh}")
@ApiOperation(value = “根据学号获取用户图标”)
@ApiImplicitParams({
@ApiImplicitParam(name = “xh”, value = “学号”, dataType = “String”)
})
public void getUserIconssss(@PathVariable(“xh”) String xh, HttpServletResponse response) throws Exception {
UserIcon userIcon = userIconService.getByAccount(xh);
if(null!=userIcon && null!=userIcon.getIconStr()){
String images = RandomUtil.uuid();
base64Decoder decoder=new base64Decoder();
byte[] bytes=decoder.decodeBuffer(userIcon.getIconStr());
File file=new File(“F:testimaimages”+File.separator +images+".jpg");
FileOutputStream fos=new FileOutputStream(file);
fos.write(bytes);
fos.flush();
fos.close();
FileUtil.downloadIcon(“F:testimaimages”, images+".jpg", response);
FileUtil.deleteImage(“F:testimaimages”,images+".jpg");
}
}

import com.test.constant.SystemConstant;
import com.test.exception.ErrorException;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;


@Slf4j
public class FileUtil {

public static void saveFile(String path, String name, InputStream in) {
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
try (BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(new File(path + “/” + name)))) {
byte[] bytes = new byte[2048];
int length;
while ((length = in.read(bytes)) != -1) {
out.write(bytes, 0, length);
}
out.flush();
in.close();
} catch (IOException e) {
log.error(“保存文件异常”, e);
}
}

public static void downloadFile(String path, String name, OutputStream out) {
File file = new File(path + File.separator + name);
if (!file.exists()) {
log.info(“文件不存在,{}”, name);
throw new ErrorException(400,“文件不存在”);
}
try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file))) {
byte[] bytes = new byte[2048];
int length;
while ((length = in.read(bytes)) != -1) {
out.write(bytes, 0, length);
}
out.flush();
out.close();
} catch (IOException e) {
log.error(“下载文件异常”, e);
}
}

public static void downloadIcon(String iconPath, String icon, HttpServletResponse response) {
File file = new File(iconPath + File.separator + icon);
if (!file.exists()) {
log.error(“图片logo不存在”);
throw new ErrorException(400,“图片logo不存在”);
}
try (
FileInputStream inputStream = new FileInputStream(file); OutputStream outputStream = response
.getOutputStream()) {
byte[] data = new byte[(int) file.length()];
inputStream.read(data);
if (icon.endsWith(“svg”)) {
response.setContentType(“image/svg+xml”);
} else {
response.setContentType(“image/png”);
}
outputStream.write(data);
outputStream.flush();
} catch (IOException e) {
log.error(“图片logo读取失败”);
e.printStackTrace();
}
}


public static void deleteImage(String path, String name) {
try {
File image = new File(path + File.separator + name);
if (image.exists()) {
image.delete();
}
image = new File(getCompressImageName(path, name));
if (image.exists()) {
image.delete();
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}

public static void deleteFile(String path, String name) {
File file;
if (path.lastIndexOf("/") == path.length() - 1) {
file = new File(path + name);
} else {
file = new File(path + “/” + name);
}
if (file.exists()) {
file.delete();
}
}

public static String getCompressImageName(String savePath, String imageName) {
StringBuffer sb = new StringBuffer(savePath);
sb.append(File.separator).append(imageName, 0, imageName.indexOf(".")).append("_compress")
.append(imageName.substring(imageName.indexOf(".")));
return sb.toString();
}


public static String saveLogo(String logoSavePath,MultipartFile logoFile, String logo) {
if (logoFile == null) {
return null;
}
if (StringUtils.isNotEmpty(logo)) {
FileUtil.deleteImage(logoSavePath, logo);
}
File file = new File(logoSavePath);
if (!file.exists()) {
file.mkdirs();
}
// 获取图片名称
String picName = UUID.randomUUID().toString().replace("-", “”);
String fileType = new MimetypesFileTypeMap().getContentType(logoFile.getOriginalFilename());
String pictureName = picName + “.” + fileType;
try (ByteArrayInputStream inputStream = new ByteArrayInputStream(logoFile.getBytes());
ByteArrayInputStream suitStream = new ByteArrayInputStream(logoFile.getBytes())) {
Thumbnails.of(inputStream).scale(1d)
.outputQuality(0.25d)
.toFile(FileUtil.getCompressImageName(logoSavePath, pictureName));
Thumbnails.of(suitStream).scale(1d).outputQuality(1d)
.toFile(logoSavePath + File.separator + pictureName);
} catch (IOException e) {
log.error(“save person image failed,” + e.getMessage());
}
return pictureName;
}

public static void validServiceIcons(MultipartFile image) {
if (image != null) {
String fileType = StringUtils.substringAfterLast(image.getOriginalFilename(), “.”);
if (!SystemConstant.IMAGE_TYPES.contains(fileType.toLowerCase())) {
throw new ErrorException(400,“图片格式不合法”);
}
}
}

public static String savedocument(String documentSavePath,MultipartFile documentFile, String documentUrl) {
if (null == documentFile) {
return null;
}
if (StringUtils.isNotEmpty(documentUrl)) {
FileUtil.deleteFile(documentSavePath, documentUrl);
}
try {
String fileName = UUID.randomUUID().toString().replace("-", “”);
String fileType = StringUtils
.substringAfterLast(documentFile.getOriginalFilename(), “.”);
fileName = fileName + “.” + fileType;
FileUtil.saveFile(documentSavePath, fileName, documentFile.getInputStream());
return fileName;
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}

}

package com.test.util;
import sun.misc.base64Decoder;
import sun.misc.base64Encoder;
import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.FileImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.*;


public class TestImageBinary {

static base64Encoder encoder = new base64Encoder();
static base64Decoder decoder = new base64Decoder();

public static void main(String[] args) {
System.out.println(getImageBinary());
base64StringToImage(getImageBinary());
System.out.println("*********************");
byte[] image2byte = image2byte(“F:testimaimagestest.jpg”);
System.out.println(image2byte);
try {
String images = RandomUtil.uuid();
ByteArrayInputStream bais = new ByteArrayInputStream(image2byte);
BufferedImage bi1 = ImageIO.read(bais);
File w2 = new File(“F:testimaimages”+File.separator+images+".jpg");//可以是jpg,png,gif格式
ImageIO.write(bi1, “jpg”, w2);//不管输出什么格式图片,此处不需改动
} catch (IOException e) {
e.printStackTrace();
}
}
/

将图片转换成二进制@return
*/
static String getImageBinary(){
File f = new File(“F:testimaimagesimages.jpg”);
BufferedImage bi;
try {
bi = ImageIO.read(f);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bi, “jpg”, baos);
byte[] bytes = baos.toByteArray();
return encoder.encodeBuffer(bytes).trim();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}


static void base64StringToImage(String base64String){
String images = RandomUtil.uuid();
try {
byte[] bytes1 = decoder.decodeBuffer(base64String);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
BufferedImage bi1 =ImageIO.read(bais);
File w2 = new File(“F:testimaimages”+images+".jpg");//可以是jpg,png,gif格式
ImageIO.write(bi1, “jpg”, w2);//不管输出什么格式图片,此处不需改动
} catch (IOException e) {
e.printStackTrace();
}
}

//图片到byte数组
public static byte[] image2byte(String path){
byte[] data = null;
FileImageInputStream input = null;
try {
input = new FileImageInputStream(new File(path));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int numBytesRead = 0;
while ((numBytesRead = input.read(buf)) != -1) {
output.write(buf, 0, numBytesRead);
}
data = output.toByteArray();
output.close();
input.close();
} catch (FileNotFoundException ex1) {
ex1.printStackTrace();
} catch (IOException ex1) {
ex1.printStackTrace();
}
return data;
}

//byte数组到图片
public static void byte2image(byte[] data,String path){
if(data.length<3||path.equals("")) return;
try{
FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
imageOutput.write(data, 0, data.length);
imageOutput.close();
System.out.println("Make Picture success,Please find image in " + path);
} catch(Exception ex) {
System.out.println("Exception: " + ex);
ex.printStackTrace();
}
}
//byte数组到16进制字符串
public static String byte2string(byte[] data){
if(data==null||data.length<=1) return “0x”;
if(data.length>200000) return “0x”;
StringBuffer sb = new StringBuffer();
int buf[] = new int[data.length];
//byte数组转化成十进制
for(int k=0;k buf[k] = data[k]<0?(data[k]+256):(data[k]);
}
//十进制转化成十六进制
for(int k=0;k if(buf[k]<16) sb.append(“0”+Integer.toHexString(buf[k]));
else sb.append(Integer.toHexString(buf[k]));
}
return “0x”+sb.toString().toUpperCase();
}


public static void testCopyImage(){
File source=new File(“E:shareWallpaperBliss.jpg”);
File desk=new File(“d:images”);
if(!desk.exists()){
desk.mkdir();
}
try {
FileInputStream inputStream=new FileInputStream(source);
FileOutputStream outputStream=new FileOutputStream(new File(“d:/images/Bliss.jpg”));
int ch=inputStream.read();
while(ch!=-1){
outputStream.write(ch);
ch=inputStream.read();
}
inputStream.close();
outputStream.close();
System.out.println(“图片复制成功!”);
} catch (FileNotFoundException e) {
System.out.println(“文件不存在:”+e.getMessage());
} catch (IOException e) {
System.out.println(“文件读取错误:”+e.getMessage());
}

}

//有问题

public static String byte2hex(byte[] b){
StringBuffer sb = new StringBuffer();
String stmp = “”;
for (int n = 0; n < b.length; n++) {
stmp = Integer.toHexString(b[n] & 0xFF);
if (stmp.length() == 1) {
sb.append(“0” + stmp);
} else {
sb.append(stmp);
}

}
return sb.toString();
}


public static byte[] hex2byte(String str) {
if (str == null){
return null;
}
str = str.trim();
int len = str.length();
if (len == 0 || len % 2 == 1){
return null;
}
byte[] b = new byte[len / 2];
try {
for (int i = 0; i < str.length(); i += 2) {
b[i / 2] = (byte) Integer.decode(“0X” + str.substring(i, i + 2)).intValue();
}
return b;
} catch (Exception e) {
return null;
}
}

}

package com.test.util;

import javax.activation.MimetypesFileTypeMap;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.UUID;


public class RandomUtil {

private static final int[] NUMBERS = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
private static final String[] CHARS = {“a”, “b”, “c”, “d”, “e”, “f”, “g”, “h”, “i”, “j”, “k”, “l”, “m”, “n”, “o”,
“p”, “q”, “r”, “s”, “t”, “u”, “v”, “w”, “x”, “y”, “z”};
private static final String[] SPECIALS = {"~", “!”, “@”, “#”, “$”, “%”, “^”, “&”, “*”, “(”, “)”, “-”, “+”};
private static final int PASSWORD_LEN = 16;
private static final int VERIFY_CODE_LEN = 6;
private static final List FILTER_CHAR = Arrays.asList(“i”, “I”, “l”, “L”,“0”,“o”,“O”);


public static String password() {
StringBuilder result = new StringBuilder();
Random typeRandom = new Random();
Random indexRandom = new Random();
for (int index = 0; index < PASSWORD_LEN; index++) {
int next = typeRandom.nextInt(4);
switch (next) {
case 0:
result.append(NUMBERS[indexRandom.nextInt(10)]);
break;
case 1:
result.append(CHARS[indexRandom.nextInt(26)]);
break;
case 2:
result.append(CHARS[indexRandom.nextInt(26)].toUpperCase());
break;
case 3:
result.append(SPECIALS[indexRandom.nextInt(13)]);
break;
default:
}
}
return result.toString();
}

public static String verifyCode() {
StringBuilder result = new StringBuilder();
Random typeRandom = new Random();
Random indexRandom = new Random();
String str;
int index = 0;
while (index < VERIFY_CODE_LEN) {
int next = typeRandom.nextInt(3);
switch (next) {
case 1:
str = CHARS[indexRandom.nextInt(26)];
break;
case 2:
str = CHARS[indexRandom.nextInt(26)].toUpperCase();
break;
default:
str = NUMBERS[indexRandom.nextInt(10)] + “”;
break;
}
if (FILTER_CHAR.contains(str)) {
continue;
}
result.append(str);
index++;
}
return result.toString();
}

public static String uuid() {
return UUID.randomUUID().toString().replace("-", “”);
}

public static void main(String[] args) {
String fileName = “images.png”;
String type = new MimetypesFileTypeMap().getContentType(fileName);
System.out.println("第二种javax.activation: "+type);
for (int index = 0; index < 10000; index++) {
System.out.println(RandomUtil.verifyCode());
}
}
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/760382.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号