`
xudongcsharp
  • 浏览: 475113 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

图片压缩得实现类(对网站优化有很大的帮助)

    博客分类:
  • Java
阅读更多
package com.sun.jsonutil;

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 come from net
*
*/
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图片压缩通用类

    使用这样的通用类,开发人员可以在项目中快速实现图片压缩功能,而无需深入研究底层的图像处理细节。这提高了开发效率,也使代码更加模块化和易于维护。在实际应用中,比如在上传图片到服务器、存储到数据库或者在...

    C# core 图片压缩 图片无损压缩 图片无损剪切 无损图片压缩 无损图片剪切

    在C# Core中进行图片处理是一项常见的任务,其中包括图片压缩和剪切操作。无损压缩和剪切技术在保持原始图像质量的同时,可以减小文件大小或改变图像的形状。以下将详细介绍C# Core中如何实现这些功能。 首先,我们...

    图片压缩节约内存

    在IT行业中,图片压缩是一个非常重要的技术,尤其是在内存管理和移动应用开发中。标题"图片压缩节约内存"直接指向了这个...而"TestCompressBitmap"可能是一个示例程序或者类,用于演示如何在实际代码中实现图片压缩。

    图片压缩工具PNG图片压缩工具压缩率高不失真

    总的来说,PNG图片压缩工具是数字内容创作者和网站开发者的重要工具,它能够帮助他们在保持图像质量的同时,有效地管理和传输大量的PNG图像资源。合理使用这类工具,可以提升用户体验,降低服务器负载,并节省宝贵的...

    图片压缩软件【压缩图片】

    在现代数字时代,图片文件占据了我们存储空间的很大一部分,特别是在摄影、设计或者社交媒体分享等领域。为了有效地管理和传输这些图片,图片压缩软件成为了必不可少的工具。"图片压缩软件【压缩图片】"是一款专注于...

    小巧实用的图片压缩工具

    “图片压缩.exe”很可能是这个图片压缩工具的可执行文件,它是程序的核心部分,用户可以通过运行这个文件来启动并使用图片压缩功能。而“Readme-说明.htm”则是一份帮助文档,通常包含了软件的使用指南、注意事项...

    图片压缩工具,简单好用,可压缩至300K以内

    本文将围绕“图片压缩工具”这一主题,深入探讨其工作原理、重要性以及如何实现图片压缩至300K以内。 图片压缩主要分为两种类型:有损压缩和无损压缩。有损压缩,如JPEG,通过牺牲部分图像质量来大幅度减小文件大小...

    蜂鸟图片压缩软件 JPG PNG 压缩

    为了优化用户体验和节省资源,图片压缩变得至关重要。"蜂鸟图片压缩软件"(Hummingbird)是专为此目的设计的工具,尤其针对JPG和PNG这两种广泛使用的图片格式。 1. **JPG和PNG格式**:JPG(Joint Photographic ...

    图片上传及压缩类

    常见的图片压缩方法有几种: 1. **质量压缩**:通过调整JPEG的质量参数,降低图片的保存质量,从而减小文件大小。这可以在`Bitmap.compress()`方法中实现,传入`Bitmap.CompressFormat.JPEG`和一个0到100之间的质量...

    图片压缩小工具

    "图片压缩小工具"很可能采用了有损压缩方式,因为通常头像对画质的要求相对较低,牺牲一定的质量换取更小的文件尺寸是可以接受的。 在描述中提到,这个工具是用C#语言开发的。C#是一种面向对象的编程语言,具有丰富...

    图片压缩工具类

    在IT行业中,图片压缩是一个非常重要的领域,尤其是在网站优化、移动应用开发以及数据存储等方面。本文将基于提供的“图片压缩工具类”主题进行详细的解析,介绍相关知识点。 首先,我们来了解一下图片压缩的基本...

    android 分享微信小程序+压缩图片优化

    本教程将深入探讨如何实现这一功能,并特别关注图片压缩优化,以确保分享过程的顺利进行。 首先,我们需要集成微信SDK。在Android项目中,通过引入微信官方提供的SDK库,可以获取到分享相关的API接口。确保在`build...

    jpg,bmp图片压缩工具

    在IT领域,图片压缩工具是图像处理中不可或缺的一部分。标题提到的"jpg,bmp图片压缩工具"主要关注的是两种常见的图像格式:JPEG(Joint Photographic Experts Group)和BMP(Bitmap)。这两种格式各有特点,但在...

    android图片压缩的处理.zip

    这个"android图片压缩的处理.zip"文件很可能是包含了一些示例代码或库,用于帮助开发者了解和实现Android平台上的图片压缩技术。下面将详细讨论Android图片压缩的基本原理、常用方法以及可能涉及到的技术点。 1. **...

    用来压缩图片大小的工具

    综上所述,这个工具——"jpgcompact.exe",是一个专注于JPEG图片压缩的实用程序,它旨在帮助用户减小图片文件的体积,以适应各种存储和传播需求,同时尽可能保持图像质量。用户可以通过调整其参数设置,找到适合自己...

    WinForm批量图片压缩工具源代码

    这个"WinForm批量图片压缩工具源代码"提供了一个很好的机会来深入理解WinForm应用程序的开发,以及图像处理和优化方面的知识。下面,我们将详细探讨相关知识点。 1. **WinForm基础**: - WinForm是Microsoft .NET ...

    图片压缩类:通过缩放来压缩 imgys.rar

    在IT行业中,图片压缩是一个非常重要的领域,尤其是在网站优化、数据传输和存储方面。本案例提供的"图片压缩类:通过缩放来压缩 imgys.rar"是一个PHP源码实现的图片压缩解决方案,它主要通过调整图片的尺寸来实现...

    Java图片压缩

    4. **Java图片压缩实现** - **读取图片**:使用`ImageIO.read()`方法从文件或流中读取图像到`BufferedImage`对象。 - **调整尺寸**:通过`BufferedImage`的`getSubimage()`或`setRGB()`方法裁剪或缩放图片,降低...

    高仿微信朋友圈图片选择+图片压缩

    这个项目旨在提供一个高度模仿微信朋友圈的图片选择功能,并结合图片压缩技术,优化用户体验并减少数据传输的负担。以下将详细介绍这两个关键知识点。 首先,我们要理解**图片选择功能**。在Android平台上,开发者...

Global site tag (gtag.js) - Google Analytics