码迷,mamicode.com
首页 > 编程语言 > 详细

Java图片上传

时间:2015-05-15 21:33:03      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:图片上传   压缩大小   

             图片上传,其实,也可以按照之前文章——文件上传的方式实现,因为图片也是文件。只要是文件,都可以用流来接收,然后把流给写出到指定的物理空间下,形成我们需要的物理文件。

             今天,我们就不用上传文件的方式,这种方式和我之前的一篇制作二维码的文章类似。首先,读文件,需要知道文件的路径,比如放在C盘下面的某个文件。然后把这个图片通过画笔方式给画出来。放到指定服务器路径下。不需要第三方插件,sun公司提供的image工具类就可以实现。

下面我们把桌面上的blue.png图片上传到服务器上。

public static String imgUpload(HttpServletRequest request,
                                   HttpServletResponse response)
        throws Exception
    {
        String resultPath = "";
        String filePath = "C:/Users/Administrator/Desktop/blue.png";
        String savePath = request.getRealPath("/save/");
        File uploadDir = new File(savePath);
        File file = new File(filePath);

        if ( !file.isFile())
        {
            return "不是文件类型";
        }
        if ( !uploadDir.exists())
        {
            uploadDir.mkdirs();
        }
        BufferedImage img = ImageIO.read(file);
        if (img != null)
        {
            BufferedImage tag = new BufferedImage(img.getWidth(),
                img.getHeight(), BufferedImage.TYPE_INT_RGB);
            tag.getGraphics().drawImage(img, 0, 0, img.getWidth(),
                img.getHeight(), null);

            int lastLength = filePath.lastIndexOf(".");
            Date date = new Date(System.currentTimeMillis());
            String strDate = new SimpleDateFormat("yyyyMMddhhmmss").format(date);
            int random = (int) (Math.random() * 99);
            String imageName = strDate + random; //以系统时间来随机的创建图片文件名
            String fileType = filePath.substring(lastLength); //获取上传图片的类型
            resultPath = savePath + imageName + fileType;
            System.out.println(resultPath);

            FileOutputStream out = new FileOutputStream(resultPath);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(tag);
            param.setQuality(0.95f, true); //95%图像       
            param.setDensityUnit(1); //像素尺寸单位.像素/英寸     
            param.setXDensity(300); //水平分辨率       
            param.setYDensity(300); //垂直分辨率 
            encoder.setJPEGEncodeParam(param);
            encoder.encode(tag);
            tag.flush();
            out.flush();
            out.close();
        return resultPath;
    }


这种方式上传图片,好处就在于,可以控制图片的大小尺寸,可以按照自己的需要进行裁剪压缩图片。








Java图片上传

标签:图片上传   压缩大小   

原文地址:http://blog.csdn.net/moyanxuan_1993_2_24/article/details/45747755

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!