IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> 图片转二进制下载预览 -> 正文阅读

[Java知识库]图片转二进制下载预览

/**

  • @auther CodeGenerator

  • @create 2022-03-07 10:56:16

  • @describe 用户图标实体类
    */
    @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;

/**

  • 根据学号获取用户图标OK
    */
    @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:\testima\images\test.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:\testima\images\”+File.separator+images+".jpg");//可以是jpg,png,gif格式
    ImageIO.write(bi1, “jpg”, w2);//不管输出什么格式图片,此处不需改动
    } catch (IOException e) {
    e.printStackTrace();
    }
    FileUtil.downloadIcon(“F:\testima\images\”, images+".jpg", response);
    return R.ok().put(“data”, value);
    }

/**

  • 根据学号获取用户图标OK
    */
    @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:\testima\images\”+File.separator+images+".jpg");//可以是jpg,png,gif格式
    ImageIO.write(bi1, “jpg”, w2);//不管输出什么格式图片,此处不需改动
    } catch (IOException e) {
    e.printStackTrace();
    }
    FileUtil.downloadIcon(“F:\testima\images\”, images+".jpg", response);
    FileUtil.deleteImage(“F:\testima\images\”,images+".jpg");
    }
    }

/**

  • 根据学号获取用户图标err
    */
    @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:\testima\images\”+File.separator+images+".jpg");//可以是jpg,png,gif格式
    ImageIO.write(bi1, “jpg”, w2);//不管输出什么格式图片,此处不需改动
    } catch (IOException e) {
    e.printStackTrace();
    }
    FileUtil.downloadIcon(“F:\testima\images\”, images+".jpg", response);
    FileUtil.deleteImage(“F:\testima\images\”,images+".jpg");
    }
    }

/**

  • 根据学号获取用户图标OK:string,err:byte[]
    */
    @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:\testima\images\”+File.separator+images+".jpg");//可以是jpg,png,gif格式
    ImageIO.write(bi1, “jpg”, w2);//不管输出什么格式图片,此处不需改动
    } catch (IOException e) {
    e.printStackTrace();
    }
    FileUtil.downloadIcon(“F:\testima\images\”, images+".jpg", response);
    FileUtil.deleteImage(“F:\testima\images\”,images+".jpg");
    }
    }

/**

  • 根据学号获取用户图标OK:string,err:byte[]
    */
    @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:\testima\images\”+File.separator +images+".jpg");
    FileOutputStream fos=new FileOutputStream(file);
    fos.write(bytes);
    fos.flush();
    fos.close();
    FileUtil.downloadIcon(“F:\testima\images\”, images+".jpg", response);
    FileUtil.deleteImage(“F:\testima\images\”,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;

/**

  • @CLassName FileUtil

  • @Description 文件操作工具类

  • @Version 1.0
    **/
    @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();
    }
    }

    /**

    • @return void
    • @Author kuai.zhang
    • @Description 删除图片
    • @Date 16:20 2019/7/18
    • @Param [savePath, imageName]
      **/
      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();
    }

    /**

    • 保存logo 先删除原先的
      */
      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:\testima\images\test.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:\testima\images\”+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:\testima\images\images.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;
      }

    /**

    • 将二进制转换为图片
    • @param base64String
      */
      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:\testima\images\”+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<data.length;k++){
    buf[k] = data[k]<0?(data[k]+256):(data[k]);
    }
    //十进制转化成十六进制
    for(int k=0;k<buf.length;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:\share\Wallpaper\Bliss.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());
      }

    }

    //有问题
    /**

    • 二进制转字符串

    • @param b

    • @return
      */
      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();
      }

    /**

    • 字符串转二进制
    • @param str 要转换的字符串
    • @return 转换后的二进制数组
      */
      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;

/**

  • @ClassName RandomUtil

  • @Description: TODO
    **/
    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”);

    /**

    • 16位
      */
      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());
    }
    }
    }

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2022-03-11 21:59:56  更:2022-03-11 22:02:12 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 10:45:36-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码