package com.zzsn.modules.kgj.controller;

import com.zzsn.modules.kgj.entity.BaseDataImage;
import com.zzsn.modules.kgj.service.BaseDataImageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Decoder;

import java.io.IOException;

/**
 * @author: 陈如意
 * @description: 文章图片
 * @date: 2021/2/23 15:16
 */
@Controller
@Slf4j
@RequestMapping("/image")
public class BaseDataImageController {
    @Autowired
    private BaseDataImageService baseDataImageService;

    /**
     * 根据传入的加密后md5值，获取base64图片
     * @param id 加入
     * @return
     * @throws IOException
     */
    @GetMapping(value = "/base/{id}",produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] getBase64(@PathVariable String id) throws IOException {
        if(StringUtils.isBlank(id)){
            return null;
        }else{
            BaseDataImage base64 = baseDataImageService.queryById(id);
            if(base64!=null){
                byte[] bytes = new BASE64Decoder().decodeBuffer(base64.getDataImage());
                for (int i = 0; i < bytes.length; ++i) {
                    if (bytes[i] < 0) {
                        bytes[i] += 256;
                    }
                }
                return bytes;
            }
            return null;
        }
    }
}
