`
gg19861207
  • 浏览: 181706 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

一个实现图片压缩的Java源代码

阅读更多

package com.itcast.util;

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 图像压缩工具
 * @author lihuoming@sohu.com
 *
 */
public class ImageSizer {
    public static final MediaTracker tracker = new MediaTracker(new Component() {
        private static final long serialVersionUID = 1234162663955668507L;}
    );
    /**
     * @param originalFile 原图像
     * @param resizedFile 压缩后的图像
     * @param width 图像宽
     * @param format 图片格式 jpg, png, gif(非动画)
     * @throws IOException
     */
    public static void resize(File originalFile, File resizedFile, int width, String format) throws IOException {
        if(format!=null && "gif".equals(format.toLowerCase())){
         resize(originalFile, resizedFile, width, 1);
         return;
        }
        FileInputStream fis = new FileInputStream(originalFile);
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        int readLength = -1;
        int bufferSize = 1024;
        byte bytes[] = new byte[bufferSize];
        while ((readLength = fis.read(bytes, 0, bufferSize)) != -1) {
            byteStream.write(bytes, 0, readLength);
        }
        byte[] in = byteStream.toByteArray();
        fis.close();
        byteStream.close();
       
     Image inputImage = Toolkit.getDefaultToolkit().createImage( in );
        waitForImage( inputImage );
        int imageWidth = inputImage.getWidth( null );
        if ( imageWidth < 1 )
           throw new IllegalArgumentException( "image width " + imageWidth + " is out of range" );
        int imageHeight = inputImage.getHeight( null );
        if ( imageHeight < 1 )
           throw new IllegalArgumentException( "image height " + imageHeight + " is out of range" );
       
        // Create output image.
        int height = -1;
        double scaleW = (double) imageWidth / (double) width;
        double scaleY = (double) imageHeight / (double) height;
        if (scaleW >= 0 && scaleY >=0) {
            if (scaleW > scaleY) {
                height = -1;
            } else {
                width = -1;
            }
        }
        Image outputImage = inputImage.getScaledInstance( width, height, java.awt.Image.SCALE_DEFAULT);
        checkImage( outputImage );       
        encode(new FileOutputStream(resizedFile), outputImage, format);       
    }   

    /** Checks the given image for valid width and height. */
    private static void checkImage( Image image ) {
       waitForImage( image );
       int imageWidth = image.getWidth( null );
       if ( imageWidth < 1 )
          throw new IllegalArgumentException( "image width " + imageWidth + " is out of range" );
       int imageHeight = image.getHeight( null );
       if ( imageHeight < 1 )
          throw new IllegalArgumentException( "image height " + imageHeight + " is out of range" );
    }

    /** Waits for given image to load. Use before querying image height/width/colors. */
    private static void waitForImage( Image image ) {
       try {
          tracker.addImage( image, 0 );
          tracker.waitForID( 0 );
          tracker.removeImage(image, 0);
       } catch( InterruptedException e ) { e.printStackTrace(); }
    }

    /** Encodes the given image at the given quality to the output stream. */
    private static void encode( OutputStream outputStream, Image outputImage, String format )
       throws java.io.IOException {
       int outputWidth  = outputImage.getWidth( null );
       if ( outputWidth < 1 )
          throw new IllegalArgumentException( "output image width " + outputWidth + " is out of range" );
       int outputHeight = outputImage.getHeight( null );
       if ( outputHeight < 1 )
          throw new IllegalArgumentException( "output image height " + outputHeight + " is out of range" );

       // Get a buffered image from the image.
       BufferedImage bi = new BufferedImage( outputWidth, outputHeight,
          BufferedImage.TYPE_INT_RGB );                                                  
       Graphics2D biContext = bi.createGraphics();
       biContext.drawImage( outputImage, 0, 0, null );
       ImageIO.write(bi, format, outputStream);
       outputStream.flush();     
    }
   
 /**
  * 缩放gif图片
  * @param originalFile 原图片
  * @param resizedFile 缩放后的图片
  * @param newWidth 宽度
  * @param quality 缩放比例 (等比例)
  * @throws IOException
  */
    private static void resize(File originalFile, File resizedFile, int newWidth, float quality) throws IOException {
        if (quality < 0 || quality > 1) {
            throw new IllegalArgumentException("Quality has to be between 0 and 1");
        }
        ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath());
        Image i = ii.getImage();
        Image resizedImage = null;
        int iWidth = i.getWidth(null);
        int iHeight = i.getHeight(null);
        if (iWidth > iHeight) {
            resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight) / iWidth, Image.SCALE_SMOOTH);
        } else {
            resizedImage = i.getScaledInstance((newWidth * iWidth) / iHeight, newWidth, Image.SCALE_SMOOTH);
        }
        // This code ensures that all the pixels in the image are loaded.
        Image temp = new ImageIcon(resizedImage).getImage();
        // Create the buffered image.
        BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null),
                                                        BufferedImage.TYPE_INT_RGB);
        // Copy image to buffered image.
        Graphics g = bufferedImage.createGraphics();
        // Clear background and paint the image.
        g.setColor(Color.white);
        g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
        g.drawImage(temp, 0, 0, null);
        g.dispose();
        // Soften.
        float softenFactor = 0.05f;
        float[] softenArray = {0, softenFactor, 0, softenFactor, 1-(softenFactor*4), softenFactor, 0, softenFactor, 0};
        Kernel kernel = new Kernel(3, 3, softenArray);
        ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
        bufferedImage = cOp.filter(bufferedImage, null);
        // Write the jpeg to a file.
        FileOutputStream out = new FileOutputStream(resizedFile);       
        // Encodes image as a JPEG data stream
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage);
        param.setQuality(quality, true);
        encoder.setJPEGEncodeParam(param);
        encoder.encode(bufferedImage);
    }
}

分享到:
评论

相关推荐

    java实现视频压缩

    在提供的压缩包中,可能包含了实现以上步骤的Java源代码,以及必要的依赖库,如jave.jar。用户可以通过导入这些代码和库,直接在自己的Java项目中实现视频压缩功能。 需要注意的是,视频压缩是一个计算密集型的任务...

    图片缩放、压缩技术java实现

    现在,让我们看看如何结合这些概念,编写一个简单的Java程序来实现图片等比缩放并压缩。首先,你需要导入必要的库,然后创建一个方法接收图片路径、目标宽度和高度,返回缩放并压缩后的图片路径。 ```java import ...

    Java 图片压缩

    以下是一个简单的Java图片压缩示例: ```java import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class ImageCompressor { public ...

    java图片压缩处理(可以压缩为任意大小

    本主题将深入探讨如何使用Java实现图片压缩,并能够将其调整到任意大小,同时保持图片质量并避免变形。 首先,我们需要理解图片压缩的基本原理。图片压缩主要有两种类型:有损压缩和无损压缩。有损压缩会牺牲一部分...

    JAVA上百实例源码以及开源项目源代码

    Java源代码实现部分,比较有意思,也具参考性。像坐标控制、旋转矩阵、定时器、生成图像、数据初始化、矩阵乘法、坐标旋转、判断是否是顺时针方向排列、鼠标按下、放开时的动作等,都可在本源码中得以体现。 Java...

    gif图片压缩(纯java实现,不依赖第三方类库)

    在IT行业中,图片压缩是一个常见的需求,特别是在网络传输和存储方面。本话题聚焦于使用纯Java实现GIF图片的压缩,不依赖任何第三方类库。这样的实现方式对于那些需要在资源有限或者对性能有特殊要求的环境中工作的...

    java蜘蛛纸牌源代码

    【标题】"java蜘蛛纸牌源代码"是一个关于使用Java编程语言实现的蜘蛛纸牌游戏的项目。这个项目不仅包含了源代码,还提供了所需的图片资源和可执行程序,使得用户可以直接运行并理解游戏的实现过程。 【源代码】在...

    JAVA毕业设计-打飞机游戏设计与实现(论文+源代码).zip

    4. `src`:源代码目录,包含了游戏的Java源代码,可以分为多个包,每个包代表游戏的不同组件或功能模块。 5. `classes`:编译后的字节码文件可能存放在这个目录下,每个类对应一个`.class`文件。 6. `lib`:库文件夹...

    Java聊天源代码.rar

    在【压缩包子文件的文件名称列表】中,"codesc.net"可能是一个目录名或文件名,通常在这种情况下,它可能包含了聊天应用的源代码文件,如Java类文件(.java)、编译后的类文件(.class)、配置文件(如XML)以及可能...

    java源码包实例源码JAVA开发源码50个合集.zip

    Java坦克大战网络对战版源代码.rar Java声音播放程序源代码.rar JAVA实现CLDC与MIDP底层编程的代码.rar Java实现HTTP连接与浏览,Java源码下载.rar Java实现的FTP连接与数据浏览程序.rar Java实现的放大镜效果附有...

    java版源代码下载

    在学习和分析Java源代码时,应注重理解类与类之间的关系,以及如何利用面向对象的设计原则,如封装、继承和多态性。此外,还需关注代码的异常处理、并发控制、性能优化等方面,这些都是高质量Java编程的关键要素。

    java开发程序源代码

    - `src/main/java`: 这个目录存放主要的Java源代码。 - `src/main/resources`: 存放非Java的资源文件,如配置文件、图片等。 - `build.gradle`或`pom.xml`: 构建文件,如果是Gradle项目,就是`build.gradle`,如果是...

    反编译Apk得到Java源代码

    反编译Apk得到Java源代码是Android应用开发中的一种重要技术,通过使用dex2jar和JD-GUI这两个工具,可以将apk文件反编译成Java源代码。下面是反编译Apk得到Java源代码的详细步骤: 一、使用dex2jar和JD-GUI反编译...

    java源代码之进销存管理系统

    【标题】"java源代码之进销存管理系统"揭示了这个项目的核心是使用Java编程语言开发的一个库存管理、销售管理和采购管理的系统。在IT领域,进销存(Inventory Management, Sales Management, Purchase Management)...

    算术算法压缩实现Java

    在提供的压缩包文件"Arithmetic"中,可能包含了实现这些功能的Java源代码文件。通过阅读和分析这些代码,可以深入理解算术压缩算法的实现细节,并可能学习到如何在实际项目中应用这种压缩技术。 总的来说,算术压缩...

    应用ImageUtil进行图片压缩(源代码)

    以下是一个简化的`ImageUtil`压缩图片的示例代码片段: ```java import java.awt.image.BufferedImage; import javax.imageio.ImageIO; public class ImageUtil { public static void compressImage(String ...

    java版图片压缩方法

    - **兼容性问题**:代码中使用了`com.sun.image.codec.jpeg`包,这是一个内部实现,可能在不同的JDK版本中存在差异,建议使用更稳定和兼容性更好的库,如`com.drew.imaging.jpeg`。 - **错误处理**:代码中加入了...

    JAVA贪吃蛇游戏毕业设计(源代码+论文)

    在【压缩包子文件的文件名称列表】中,我们看到的是整个项目打包在一起的文件,其中可能包括Java源代码文件(.java)、编译后的类文件(.class)、项目配置文件、资源文件(如图片、音频等)以及毕业设计论文文档...

    java工程源代码实例

    在Java编程领域,一个"java工程源代码实例"通常指的是包含了一系列类、接口、方法和其他相关资源的项目,这些组合起来构成了一个可运行的程序。Java工程是开发人员用来组织和管理代码的方式,使得代码更加模块化,...

    java 3D 魔方源代码带图片

    Java 3D 魔方源代码是一种使用Java编程语言实现的三维魔方模拟软件。这个项目名为"MoFang-2006-9-18修正版",表明这是一个在2006年9月18...同时,对于有兴趣了解和实现3D魔方算法的人来说,源代码也是一个宝贵的参考。

Global site tag (gtag.js) - Google Analytics