java 上传图片 二进制保存到 mysql 请求图片二进制转化为图片 cxf rest jax-rs

1.上传   cxf rest 接口 图片转成二进制 保存到mysql  数据库的数据类型选择  blob

@POST
	@Path("/uploadimagebyte")
	@Consumes("multipart/form-data")
	public Response downloadFileByForm(
			@Multipart(value = "id", type = "text/plain") String id,
			@Multipart(value = "name", type = "text/plain") String name,
			@Multipart(value = "file", type = "image/png") Attachment image);

@Override
	public Response downloadFileByForm(
			@Multipart(value = "id", type = "text/plain") String id,
			@Multipart(value = "name", type = "text/plain") String name,
			@Multipart(value = "file", type = "image/png") Attachment image) {
		final int max_upsize = 200 * 1024; // 头像最大文件上传大小
		final int max_size = 60 * 1024; // 头像最大文件大小
		final int max_height = 600;
		final int max_weight = 600;
		try {
			// 将图片压缩并装入byte
		
			Image jimage = ImageIO
					.read(image.getDataHandler().getInputStream());
			int[] size = ImageUtil.getSize(max_weight, max_height, jimage);
			byte[] pic_bytes = ImageUtil.resize(size[0], size[1], 1f, jimage);
			System.out.println("photo size=" + pic_bytes.length);
			// 大小判断
			if (pic_bytes == null || pic_bytes.length > max_size) {
				// 不符合的话可以在这里返回 失败
				// 比如:
				// ResponseBuilder response = Response.status(500);
				// return response.build();
			}
			// 这里数据库入库
			// 构造Response
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		ResponseBuilder response = Response.ok();
		return response.build();
	}

引用的各种package 

import java.awt.Image;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.activation.DataHandler;
import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.BeanParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.apache.cxf.jaxrs.ext.multipart.Multipart;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;


2. 下载 保存图片 二进制转图片  

这里要用GET

@GET
	@Path("/downloadpic")
	public Response downloadpic();


@Override
	public Response downloadpic() {
		//pic_bytes 是从数据库查出来的图片的二进制 byte[]
			ResponseBuilder response = Response.ok(pic_bytes);
			response.header("Content-Type", "image/jpeg");
		return response.build();
	}



附上一个 iamge的帮助类


package com.weds.framework.core.utils;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.weds.framework.core.utils.SystemConstant.WatermarkPosition;

public class ImageUtil {

	 // 获取img标签正则
    private static final String IMGURL_REG = "]*?>";
    // 获取src路径的正则
    private static final String IMGSRC_REG = "(http://7xqgf8.com1.z0.glb.clouddn.com\"?(.*?))(\"|>|\\s+)";

    /**
     * 图片缩放(图片等比例缩放为指定大小,空白部分以白色填充)
     *
     * @param srcBufferedImage 源图片
     * @param destFile         缩放后的图片文件
     */
    public static void zoom(BufferedImage srcBufferedImage, File destFile, int destHeight, int destWidth) {
        try {
            int imgWidth = destWidth;
            int imgHeight = destHeight;
            int srcWidth = srcBufferedImage.getWidth();
            int srcHeight = srcBufferedImage.getHeight();
            if (srcHeight >= srcWidth) {
                imgWidth = (int) Math.round(((destHeight * 1.0 / srcHeight) * srcWidth));
            } else {
                imgHeight = (int) Math.round(((destWidth * 1.0 / srcWidth) * srcHeight));
            }
            BufferedImage destBufferedImage = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics2D = destBufferedImage.createGraphics();
            graphics2D.setBackground(Color.WHITE);
            graphics2D.clearRect(0, 0, destWidth, destHeight);
            graphics2D.drawImage(srcBufferedImage.getScaledInstance(imgWidth, imgHeight, Image.SCALE_SMOOTH), (destWidth / 2) - (imgWidth / 2), (destHeight / 2) - (imgHeight / 2), null);
            graphics2D.dispose();
            ImageIO.write(destBufferedImage, "JPEG", destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加图片水印
     *
     * @param srcBufferedImage 需要处理的源图片
     * @param destFile         处理后的图片文件
     * @param watermarkFile    水印图片文件
     */
    public static void imageWatermark(BufferedImage srcBufferedImage, File destFile, File watermarkFile, WatermarkPosition watermarkPosition, int alpha) {
        try {
            int srcWidth = srcBufferedImage.getWidth();
            int srcHeight = srcBufferedImage.getHeight();
            BufferedImage destBufferedImage = new BufferedImage(srcWidth, srcHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics2D = destBufferedImage.createGraphics();
            graphics2D.setBackground(Color.WHITE);
            graphics2D.clearRect(0, 0, srcWidth, srcHeight);
            graphics2D.drawImage(srcBufferedImage.getScaledInstance(srcWidth, srcHeight, Image.SCALE_SMOOTH), 0, 0, null);

            if (watermarkFile != null && watermarkFile.exists() && watermarkPosition != null && watermarkPosition != WatermarkPosition.no) {
                BufferedImage watermarkBufferedImage = ImageIO.read(watermarkFile);
                int watermarkImageWidth = watermarkBufferedImage.getWidth();
                int watermarkImageHeight = watermarkBufferedImage.getHeight();
                graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha / 100.0F));
                int x = 0;
                int y = 0;
                if (watermarkPosition == WatermarkPosition.topLeft) {
                    x = 0;
                    y = 0;
                } else if (watermarkPosition == WatermarkPosition.topRight) {
                    x = srcWidth - watermarkImageWidth;
                    y = 0;
                } else if (watermarkPosition == WatermarkPosition.center) {
                    x = (srcWidth - watermarkImageWidth) / 2;
                    y = (srcHeight - watermarkImageHeight) / 2;
                } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
                    x = 0;
                    y = srcHeight - watermarkImageHeight;
                } else if (watermarkPosition == WatermarkPosition.bottomRight) {
                    x = srcWidth - watermarkImageWidth;
                    y = srcHeight - watermarkImageHeight;
                }
                graphics2D.drawImage(watermarkBufferedImage, x, y, watermarkImageWidth, watermarkImageHeight, null);
            }
            graphics2D.dispose();
            ImageIO.write(destBufferedImage, "JPEG", destFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 图片缩放并添加图片水印(图片等比例缩放为指定大小,空白部分以白色填充)
     *
     * @param srcBufferedImage 需要处理的图片
     * @param destFile         处理后的图片文件
     * @param watermarkFile    水印图片文件
     */
    public static void zoomAndWatermark(BufferedImage srcBufferedImage, File destFile, int destHeight, int destWidth, File watermarkFile, WatermarkPosition watermarkPosition, int alpha) {
        try {
            int imgWidth = destWidth;
            int imgHeight = destHeight;
            int srcWidth = srcBufferedImage.getWidth();
            int srcHeight = srcBufferedImage.getHeight();
            if (srcHeight >= srcWidth) {
                imgWidth = (int) Math.round(((destHeight * 1.0 / srcHeight) * srcWidth));
            } else {
                imgHeight = (int) Math.round(((destWidth * 1.0 / srcWidth) * srcHeight));
            }

            BufferedImage destBufferedImage = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics2D = destBufferedImage.createGraphics();
            graphics2D.setBackground(Color.WHITE);
            graphics2D.clearRect(0, 0, destWidth, destHeight);
            graphics2D.drawImage(srcBufferedImage.getScaledInstance(imgWidth, imgHeight, Image.SCALE_SMOOTH), (destWidth / 2) - (imgWidth / 2), (destHeight / 2) - (imgHeight / 2), null);
            if (watermarkFile != null && watermarkFile.exists() && watermarkPosition != null && watermarkPosition != WatermarkPosition.no) {
                BufferedImage watermarkBufferedImage = ImageIO.read(watermarkFile);
                int watermarkImageWidth = watermarkBufferedImage.getWidth();
                int watermarkImageHeight = watermarkBufferedImage.getHeight();
                graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha / 100.0F));
                int x = 0;
                int y = 0;
                if (watermarkPosition == WatermarkPosition.topLeft) {
                    x = 0;
                    y = 0;
                } else if (watermarkPosition == WatermarkPosition.topRight) {
                    x = destWidth - watermarkImageWidth;
                    y = 0;
                } else if (watermarkPosition == WatermarkPosition.center) {
                    x = (destWidth - watermarkImageWidth) / 2;
                    y = (destHeight - watermarkImageHeight) / 2;
                } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
                    x = 0;
                    y = destHeight - watermarkImageHeight;
                } else if (watermarkPosition == WatermarkPosition.bottomRight) {
                    x = destWidth - watermarkImageWidth;
                    y = destHeight - watermarkImageHeight;
                }
                graphics2D.drawImage(watermarkBufferedImage, x, y, watermarkImageWidth, watermarkImageHeight, null);
            }
            graphics2D.dispose();
            ImageIO.write(destBufferedImage, "JPEG", destFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取图片文件的类型.
     *
     * @param uploadFile 图片文件对象.
     * @return 图片文件类型
     */
    public static String getImageFormatName(File uploadFile) {
        try {
            ImageInputStream imageInputStream = ImageIO.createImageInputStream(uploadFile);
            Iterator iterator = ImageIO.getImageReaders(imageInputStream);
            if (!iterator.hasNext()) {
                return null;
            }
            ImageReader imageReader = (ImageReader) iterator.next();
            imageInputStream.close();
            return imageReader.getFormatName().toLowerCase();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String convertToWeChatSize(String origin) {
        String result = origin;
        Pattern p = Pattern.compile(IMGURL_REG, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(origin);
        String imgUrl = null;
        String imgSrc = null;
        while (m.find()) {
            imgUrl = m.group();
            Matcher matcher = Pattern.compile(IMGSRC_REG).matcher(imgUrl);
            String newUrl = null;
            while (matcher.find()) {
                imgSrc = matcher.group(1);
                System.out.println(matcher.group(1));
                newUrl = matcher.replaceAll(imgSrc + "-o\"");
            }
            if (newUrl != null) {
                result = m.replaceAll(newUrl);
            }
        }
        return result;
    }
    /**
     * function: 通过目标对象的大小和标准(指定)大小计算出图片缩小的比例
     * @author hoojo
     * @createDate 2012-2-6 下午04:41:48
     * @param targetWidth 目标的宽度
     * @param targetHeight 目标的高度
     * @param standardWidth 标准(指定)宽度
     * @param standardHeight 标准(指定)高度
     * @return 最小的合适比例
     */
    public static double getScaling(double targetWidth, double targetHeight, double standardWidth, double standardHeight) {
        double widthScaling = 0d;
        double heightScaling = 0d;
        if (targetWidth > standardWidth) {
            widthScaling = standardWidth / (targetWidth * 1.00d);
        } else {
            widthScaling = 1d;
        }
        if (targetHeight > standardHeight) {
            heightScaling = standardHeight / (targetHeight * 1.00d);
        } else {
            heightScaling = 1d;
        }
        return Math.min(widthScaling, heightScaling);
    }
    /**
     * function: 通过指定大小和图片的大小,计算出图片缩小的合适大小
     * @author hoojo
     * @createDate 2012-2-6 下午05:53:10
     * @param width 指定的宽度
     * @param height 指定的高度
     * @param image 图片文件
     * @return 返回宽度、高度的int数组
     */
    public static int[] getSize(int width, int height, Image image) {
        int targetWidth = image.getWidth(null);
        int targetHeight = image.getHeight(null);
        double scaling = getScaling(targetWidth, targetHeight, width, height);
        long standardWidth = Math.round(targetWidth * scaling);
        long standardHeight = Math.round(targetHeight * scaling);
        return new int[] { Integer.parseInt(Long.toString(standardWidth)), Integer.parseInt(String.valueOf(standardHeight)) };
    }
 
    /**
     * function: 可以设置图片缩放质量,并且可以根据指定的宽高缩放图片
     * @author hoojo
     * @createDate 2012-2-7 上午11:01:27
     * @param width 缩放的宽度
     * @param height 缩放的高度
     * @param quality 图片压缩质量,最大值是1; Some guidelines: 0.75 high quality、0.5  medium quality、0.25 low quality
     * @param targetImage 即将缩放的目标图片
     * @return 图片二进制
     * @throws ImageFormatException
     * @throws IOException
     */
    public static byte[] resize(int width, int height, Float quality, Image targetImage) throws ImageFormatException, IOException {
        width = Math.max(width, 1);
        height = Math.max(height, 1);
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        image.getGraphics().drawImage(targetImage, 0, 0, width, height, null);
        
        ByteArrayOutputStream fos = new ByteArrayOutputStream();
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
        
        if (quality == null || quality <= 0) {
            quality = null;
        }
        /** 设置图片压缩质量 */  
        if(quality != null)
        {
	        JPEGEncodeParam encodeParam = JPEGCodec.getDefaultJPEGEncodeParam(image); 
	        encodeParam.setQuality(quality, true);
	        encoder.encode(image, encodeParam);  
        }
        else
        {
        	encoder.encode(image);
        }
 
        image.flush();

        byte[] jout = fos.toByteArray();
        
        fos.close();
        
        return jout;
    }
}








你可能感兴趣的:(java)