Java图片上传

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

             今天,我们就不用上传文件的方式,这种方式和我之前的一篇制作二维码的文章类似。首先,读文件,需要知道文件的路径,比如放在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;
    }


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








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陌谚轩

你的鼓励将是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值