java图片处理代码

简介: java图片处理代码

下载图片

判断宽高

小工具

package utilw;
 
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
 
import javax.imageio.ImageIO;
 
public class PicUtil {
    public static void main(String[] args) throws FileNotFoundException,
            IOException {
        PicUtil picUtil = new PicUtil();
        picUtil.getImgWidthAndHeight();
        picUtil.getImgWidthAndHeight1();
        picUtil.getLocalImgWidthAndHeight();
        // picUtil.downloadPicture("https://mmbiz.qpic.cn/mmbiz_jpg/Z6bicxIx5naJibicqgjczUbqnBPkVz1S9cicyUWR5fg2Ku1DjfXUNlC33ZLR4NI6xHn2ib5HicwbpmZcq2fSNnhuazyw/640?wx_fmt=jpeg",
        // "E:/test.jpg");
    }
 
    /**
     * @param 链接url下载图片
     * @param urlStr图片网络地址
     * @param 图片本地存放路径
     */
    public void downloadPicture(String urlStr, String imagePathName) {
        URL url = null;
        DataInputStream dataInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            url = new URL(urlStr);
            dataInputStream = new DataInputStream(url.openStream());
            fileOutputStream = new FileOutputStream(new File(imagePathName));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
 
            byte[] buffer = new byte[1024];
            int length;
            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            // byte[] context = output.toByteArray();
            fileOutputStream.write(output.toByteArray());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
                if (dataInputStream != null) {
                    dataInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    /**
     * @param 获取服务器上的图片宽高
     * @throws FileNotFoundException
     * @throws IOException
     */
    public void getImgWidthAndHeight() throws FileNotFoundException,
            IOException {
 
        URL url = new URL(
                "http://img.mall.tcl.com/dev1/0/000/148/0000148235.fid");
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        BufferedImage image = ImageIO.read(connection.getInputStream());
        int srcWidth = image.getWidth(); // 源图宽度
        int srcHeight = image.getHeight(); // 源图高度
 
        System.out.println("srcWidth = " + srcWidth);
        System.out.println("srcHeight = " + srcHeight);
 
    }
 
    /**
     * @param 获取服务器上的图片宽高
     * @param http
     *            ://img.mall.tcl.com/dev1/0/000/148/0000148235.fid
     * @throws IOException
     */
    public void getImgWidthAndHeight1() throws IOException {
        InputStream murl = new URL(
                "http://img.mall.tcl.com/dev1/0/000/148/0000148235.fid")
                .openStream();
        BufferedImage sourceImg = ImageIO.read(murl);
        System.out.println(sourceImg.getWidth()); // 源图宽度
        System.out.println(sourceImg.getHeight()); // 源图高度
    }
 
    /**
     * @param 本地图片宽高
     * */
    public void getLocalImgWidthAndHeight() throws IOException {
        File picture = new File("E:/test.jpg");
        BufferedImage sourceImg = ImageIO.read(new FileInputStream(picture));
        System.out.println(String.format("%.1f", picture.length() / 1024.0));// 源图大小
        System.out.println(sourceImg.getWidth()); // 源图宽度
        System.out.println(sourceImg.getHeight()); // 源图高度
 
    }
 
}

补充

package util;
 
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
import javax.imageio.ImageIO;
 
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
 
public class PicToStr {
    /**
     * 将图片文件转为字符串
     * 
     * @param imgFile
     * @return
     */
    public static String getImageStr(String imgFile) {
        // 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
        // String imgFile = "d:\\111.jpg";// 待处理的图片
        InputStream in = null;
        byte[] data = null;
        // 读取图片字节数组
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        // 返回Base64编码过的字节数组字符串
        return encoder.encode(data);
    }
 
    /**
     * 将图片文件转为byte数字
     * 
     * @param imgFile
     * @return
     */
    public static byte[] getImageByte(String imgFile) {
        // 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
        // String imgFile = "d:\\111.jpg";// 待处理的图片
        InputStream in = null;
        byte[] data = null;
        // 读取图片字节数组
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 返回Base64编码过的字节数组字符串
        return data;
    }
 
    /**
     * 将字符串转为图片
     * 
     * @param imgStr
     * @return
     */
    public static boolean generateImage(String imgStr, String imgFile)
            throws Exception {
        // 对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) // 图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            // 生成jpeg图片
            String imgFilePath = imgFile;// 新生成的图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            throw e;
        }
    }
 
    /**
     * 图片是否符合 jpg gjf png格式
     * 
     * @param imgStr
     * @return
     */
    public static boolean isRightFormat(String format) {
 
        return (format.equals("jpg") || format.equals("gif") || format
                .equals("png")) ? true : false;
    }
 
    /**
     * 对图片进行放大
     * 
     * @param originalImage
     *            原始图片
     * @param times
     *            放大倍数
     * @return
     */
    public static BufferedImage zoomInImage(BufferedImage originalImage,
            Integer times) {
 
        int width = originalImage.getWidth() * times;
        int height = originalImage.getHeight() * times;
 
        BufferedImage newImage = new BufferedImage(width, height,
                originalImage.getType());
        Graphics g = newImage.getGraphics();
        g.drawImage(originalImage, 0, 0, width, height, null);
        g.dispose();
        return newImage;
    }
 
    /**
     * 对图片进行放大
     * 
     * @param srcPath
     *            原始图片路径(绝对路径)
     * @param newPath
     *            放大后图片路径(绝对路径)
     * @param times
     *            放大倍数
     * @return 是否放大成功
     */
    public static boolean zoomInImage(String srcPath, String newPath,
            Integer times) {
 
        BufferedImage bufferedImage = null;
        try {
 
            File of = new File(srcPath);
            if (of.canRead()) {
 
                bufferedImage = ImageIO.read(of);
 
            }
        } catch (Exception e) {
            // TODO: 打印日志
            return false;
        }
        if (bufferedImage != null) {
 
            bufferedImage = zoomInImage(bufferedImage, times);
            try {
                // TODO: 这个保存路径需要配置下子好一点
                // 保存修改后的图像,全部保存为JPG格式
                ImageIO.write(bufferedImage, "JPG", new File(newPath));
            } catch (IOException e) {
                // TODO 打印错误信息
                return false;
            }
        }
        return true;
 
    }
 
    /**
     * 对图片进行缩小
     * 
     * @param originalImage
     *            原始图片
     * @param times
     *            缩小倍数
     * @return 缩小后的Image
     */
    public static BufferedImage zoomOutImage(BufferedImage originalImage,
            Integer times) {
        int width = originalImage.getWidth() / times;
        int height = originalImage.getHeight() / times;
        BufferedImage newImage = new BufferedImage(width, height,
                originalImage.getType());
        Graphics g = newImage.getGraphics();
        g.drawImage(originalImage, 0, 0, width, height, null);
        g.dispose();
        return newImage;
    }
 
    /**
     * 对图片进行放大
     * 
     * @param srcPath
     *            原始图片路径(绝对路径)
     * @param newPath
     *            放大后图片路径(绝对路径)
     * @param times
     *            放大倍数
     * @return 是否放大成功
     */
    public static boolean zoomOutImage(String srcPath, String newPath,
            Integer times) {
        BufferedImage bufferedImage = null;
        try {
            File of = new File(srcPath);
            if (of.canRead()) {
                bufferedImage = ImageIO.read(of);
            }
        } catch (IOException e) {
            // TODO: 打印日志
            return false;
        }
        if (bufferedImage != null) {
            bufferedImage = zoomOutImage(bufferedImage, times);
            try {
                // TODO: 这个保存路径需要配置下子好一点
                // 保存修改后的图像,全部保存为JPG格式
                ImageIO.write(bufferedImage, "JPG", new File(newPath));
            } catch (IOException e) {
                // TODO 打印错误信息
                return false;
            }
        }
        return true;
    }
 
    public static void main(String[] args) {
        String imageStr = getImageStr("C:/Users/##/Desktop/img/2f738bd4b31c870183e862c22b7f9e2f0708ffbc.jpg");
        System.out.println(imageStr);
        try {
            generateImage(imageStr, "C:/Users/##/Desktop/xingxing.jpg");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
 
        System.exit(-1);
        boolean testIn = zoomInImage("E:/11.jpg", "E:\\in.jpg", 4);
        if (testIn) {
            System.out.println("in ok");
        }
        boolean testOut = zoomOutImage("E:/11.jpg", "E:\\out.jpg", 4);
        if (testOut) {
            System.out.println("out ok");
        }
    }
}
目录
相关文章
|
2天前
|
存储 算法 安全
深入理解Java集合框架:基础类型与代码效率优化
Java集合框架是编程的核心工具,包括List、Set、Queue和Map接口及多种实现类,如ArrayList、LinkedList、HashSet、TreeSet等。理解它们的内部机制有助于优化代码。选择适合的集合类型、避免类型转换、使用并发集合和管理容量可以提升效率。深入学习这些概念能改善代码性能和可维护性。
|
2天前
|
存储 安全 Java
Java集合框架核心组件理解这些基础类型能优化代码效率。
【6月更文挑战第21天】Java集合框架核心组件:ArrayList快速随机访问,适合大量查找;LinkedList擅于插入删除,不适于随机访问;HashMap是键值对存储,O(1)查找删除。选择取决于应用场景:频繁访问选ArrayList,频繁增删选LinkedList,键值查找选HashMap。理解这些基础类型能优化代码效率。
7 1
|
3天前
|
Java
【代码诗人】Java线程的生与死:一首关于生命周期的赞歌!
【6月更文挑战第19天】Java线程生命周期,如诗般描绘了从新建到死亡的旅程:创建后待命,`start()`使其就绪,获得CPU则运行,等待资源则阻塞,任务完或中断即死亡。理解生命周期,善用锁、线程池,优雅处理异常,确保程序高效稳定。线程管理,既是艺术,也是技术。
|
3天前
|
Java
【代码诗人】Java线程的生与死:一首关于生命周期的赞歌!
【6月更文挑战第19天】在Java中,线程经历新建、就绪、运行、阻塞和死亡5个阶段。通过`start()`从新建转为就绪,进而可能运行;阻塞可能因等待资源;完成任务或中断后死亡。管理线程生命周期涉及合理使用锁、线程池、异常处理和优雅关闭,如使用`volatile`和中断标志。了解这些,能提升程序效率和稳定性。
|
4天前
|
Java 程序员 开发者
【程序员必修课】那些年,我们踩过的Java坑:自定义异常,让你的代码不再“捉急”!
【6月更文挑战第19天】Java异常处理不仅是错误处理,更是程序健壮性的体现。自定义异常能提供更精确的错误信息,便于问题定位。通过继承`Exception`创建自定义异常类,如`NegativeValueException`,可使代码更优雅,降低维护难度。自定义异常还能携带额外信息,如错误代码,增强企业级应用的错误处理能力。善用自定义异常,提升代码质量和开发效率,是优秀编程实践的重要组成部分。
|
3天前
|
算法 搜索推荐 Java
二叉树的基本概念、常见操作以及如何使用Java代码
二叉树的基本概念、常见操作以及如何使用Java代码
8 1
|
1天前
|
存储 Java 编译器
使用ASM来书写Java代码
使用ASM来书写Java代码
9 0
|
2天前
分享JavaWeb中filter过滤器的案例妙用 - 脏话过滤/编码过滤/代码过滤
分享JavaWeb中filter过滤器的案例妙用 - 脏话过滤/编码过滤/代码过滤
5 0
|
4天前
|
安全 Java 程序员
💥JAVA世界里的“拆弹专家”:try-catch-finally如何拯救你的代码?
【6月更文挑战第18天】Java异常处理的关键是`try-catch-finally`,它确保程序在遇到错误时不崩溃。例如,在文件操作中,`try`块尝试读/写文件,`catch`捕获如FileNotFoundException或IOException,打印错误信息,而`finally`确保资源释放。通过这种方式,代码能优雅处理异常,增强健壮性。
|
4天前
|
存储 安全 Java
Java Map新玩法:探索HashMap和TreeMap的高级特性,让你的代码更强大!
【6月更文挑战第18天】在Java中,Map的两大代表HashMap和TreeMap提供高效键值对操作。HashMap允许设定初始容量和加载因子以优化性能,非线程安全,可借助synchronized或ConcurrentHashMap处理多线程。遍历可通过entrySet()、keySet()和values()。而TreeMap依据键进行排序,支持自然排序和自定义Comparator,提供范围查询、获取首尾键的功能,适用于需有序遍历的场景。理解和利用这些特性能增强代码功能和效率。