「java实现缩略图」java 缩放图片

博主:adminadmin 2022-12-07 18:12:09 93

本篇文章给大家谈谈java实现缩略图,以及java 缩放图片对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

java上传图片 生成缩略图,如果上传的图片尺寸比较小就压缩处理

//将图按比例缩小。

public static BufferedImage resize(BufferedImage source, int targetW, int targetH) {

// targetW,targetH分别表示目标长和宽

int type = source.getType();

BufferedImage target = null;

double sx = (double) targetW / source.getWidth();

double sy = (double) targetH / source.getHeight();

//这里想实现在targetW,targetH范围内实现等比缩放。如果不需要等比缩放

//则将下面的if else语句注释即可

if(sxsy)

{

sx = sy;

targetW = (int)(sx * source.getWidth());

}else{

sy = sx;

targetH = (int)(sy * source.getHeight());

}

if (type == BufferedImage.TYPE_CUSTOM) { //handmade

ColorModel cm = source.getColorModel();

WritableRaster raster = cm.createCompatibleWritableRaster(targetW, targetH);

boolean alphaPremultiplied = cm.isAlphaPremultiplied();

target = new BufferedImage(cm, raster, alphaPremultiplied, null);

} else

target = new BufferedImage(targetW, targetH, type);

Graphics2D g = target.createGraphics();

//smoother than exlax:

g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY );

g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));

g.dispose();

return target;

}

public static void saveImageAsJpg (String fromFileStr,String saveToFileStr,int width,int hight)

throws Exception {

BufferedImage srcImage;

// String ex = fromFileStr.substring(fromFileStr.indexOf("."),fromFileStr.length());

String imgType = "JPEG";

if (fromFileStr.toLowerCase().endsWith(".png")) {

imgType = "PNG";

}

// System.out.println(ex);

File saveFile=new File(saveToFileStr);

File fromFile=new File(fromFileStr);

srcImage = ImageIO.read(fromFile);

if(width 0 || hight 0)

{

srcImage = resize(srcImage, width, hight);

}

ImageIO.write(srcImage, imgType, saveFile);

}

public static void main (String argv[]) {

try{

//参数1(from),参数2(to),参数3(宽),参数4(高)

saveImageAsJpg("C:\\Documents and Settings\\xugang\\桌面\\tmr-06.jpg",

"C:\\Documents and Settings\\xugang\\桌面\\2.jpg",

120,120);

} catch(Exception e){

e.printStackTrace();

}

}

java实现图片预览功能,可以显示缩列图,具有上下页的功能求技术支持

把图片按照规定的比例压缩,然后保存至FTP,列表读取缩略图,单击显示原图。

/**

     * 压缩图片方法一(高质量)

     * @param oldFile 将要压缩的图片

     * @param width 压缩宽

     * @param height 压缩高

     * @param smallIcon 压缩图片后,添加的扩展名(在图片后缀名前添加)

     * @param quality 压缩质量 范围:i0.0-1.0/i 高质量:i0.75/i 中等质量:i0.5/i 低质量:i0.25/i

     * @param percentage 是否等比压缩 若true宽高比率将将自动调整

     */

    public static void compressImage(String oldFile, int width, int height, String smallIcon,

            float quality, boolean percentage) {

        try {

            File file = new File(oldFile);

            

            // 验证文件是否存在

            if(!file.exists())

                throw new FileNotFoundException("找不到原图片!");

            

            // 获取图片信息

            BufferedImage image = ImageIO.read(file);

            int orginalWidth = image.getWidth();

            int orginalHeight = image.getHeight();

            

            // 验证压缩图片信息

            if (width = 0 || height = 0 || !Pattern.matches("^[1-9]\\d*$", String.valueOf(width))

                    || !Pattern.matches("^[1-9]\\d*$", String.valueOf(height)))

                throw new Exception("图片压缩后的高宽有误!");

            

            // 等比压缩

            if (percentage) {

                double rate1 = ((double) orginalWidth) / (double) width + 0.1;

                double rate2 = ((double) orginalHeight) / (double) height + 0.1;

                double rate = rate1  rate2 ? rate1 : rate2;

                width = (int) (((double) orginalWidth) / rate);

                height = (int) (((double) orginalHeight) / rate);

            }

            

            // 压缩后的文件名

            String filePrex = oldFile.substring(0, oldFile.lastIndexOf('.'));

            String newImage = filePrex + smallIcon + oldFile.substring(filePrex.length());

            // 压缩文件存放位置

            File savedFile = new File(newImage);

            // 创建一个新的文件

            savedFile.createNewFile();

            // 创建原图像的缩放版本

            Image image2 = image.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING);

            // 创建数据缓冲区图像

            BufferedImage bufImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

            // 创建一个Graphics2D

            Graphics2D g2 = bufImage.createGraphics();

            // 重绘图像

            g2.drawImage(image2, 0, 0, width, height, null);

            g2.dispose();

            

            // 过滤像素矩阵

            float[] kernelData = { 

                    -0.125f, -0.125f, -0.125f, 

                    -0.125f, 2, -0.125f, -0.125f, 

                    -0.125f, -0.125f };

            Kernel kernel = new Kernel(3, 3, kernelData);

            

            // 按核数学源图像边缘的像素复制为目标中相应的像素输出像素

            ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);

            // 转换像素

            bufImage = cOp.filter(bufImage, null);

            FileOutputStream out = new FileOutputStream(savedFile);

            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufImage);

            // 设置压缩质量

            param.setQuality(quality, true);

            encoder.encode(bufImage, param);

            out.close();

            System.out.println(newImage);

        } catch (Exception e) {

            e.printStackTrace();

            System.out.println("压缩失败!" + e.getMessage());

        }

    }

java如何实现把一个大图片压缩到指定大小的图片且长宽比不变

也就是图片压缩,可以不修改任何大小的压缩(速度快),也可等比例修改大小压缩(较慢)

下面这是一段等比例缩小图片的方法。

public String compressPic(String inputDir, String outputDir,

String inputFileName, String outputFileName, int width,

int height, boolean gp,String hzm) {

try {

if (!image.exists()) {

return "";

}

Image img = ImageIO.read(image);

// 判断图片格式是否正确

if (img.getWidth(null) == -1) {

return "no";

} else {

int newWidth; int newHeight;

// 判断是否是等比缩放

if (gp == true) {

// 为等比缩放计算输出的图片宽度及高度

double rate1 = ((double) img.getWidth(null)) / (double) width ;

double rate2 = ((double) img.getHeight(null)) / (double) height ;

// 根据缩放比率大的进行缩放控制

double rate = rate1 rate2 ? rate1 : rate2;

newWidth = (int) (((double) img.getWidth(null)) / rate);

newHeight = (int) (((double) img.getHeight(null)) / rate);

} else {

newWidth = img.getWidth(null); // 输出的图片宽度

newHeight = img.getHeight(null); // 输出的图片高度

}

BufferedImage tag = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_INT_RGB);

/*

* Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的

* 优先级比速度高 生成的图片质量比较好 但速度慢

*/

Image im = img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);

tag.getGraphics().drawImage(im, 0, 0, null);

FileOutputStream out = new FileOutputStream(outputDir + outputFileName);

//JPEGImageEncoder可适用于其他图片类型的转换

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

encoder.encode(tag);

out.close();

}

} catch (IOException ex) {

ex.printStackTrace();

}

return "ok";

}

javaWeb怎么实现根据内容生成缩略图

package com.hoo.util;

 

import java.awt.Image;

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.net.MalformedURLException;

import java.net.URL;

import javax.imageio.ImageIO;

import com.sun.image.codec.jpeg.ImageFormatException;

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

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

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

 

/**

 * bfunction:/b 缩放图片工具类,创建缩略图、伸缩图片比例

 * @author hoojo

 * @createDate 2012-2-3 上午10:08:47

 * @file ScaleImageUtils.java

 * @package com.hoo.util

 * @version 1.0

 */

public abstract class ScaleImageUtils {

 

    private static final float DEFAULT_SCALE_QUALITY = 1f;

    private static final String DEFAULT_IMAGE_FORMAT = ".jpg"; // 图像文件的格式 

    private static final String DEFAULT_FILE_PATH = "C:/temp-";

    

    /**

     * bfunction:/b 设置图片压缩质量枚举类;

     * Some guidelines: 0.75 high quality、0.5  medium quality、0.25 low quality

     * @author hoojo

     * @createDate 2012-2-7 上午11:31:45

     * @file ScaleImageUtils.java

     * @package com.hoo.util

     * @project JQueryMobile

     * @version 1.0

     */

    public enum ImageQuality {

        max(1.0f), high(0.75f), medium(0.5f), low(0.25f);

        

        private Float quality;

        public Float getQuality() {

            return this.quality;

        }

        ImageQuality(Float quality) {

            this.quality = quality;

        }

    }

    

    private static Image image;

    

    /**

     * bfunction:/b 通过目标对象的大小和标准(指定)大小计算出图片缩小的比例

     * @author hoojo

     * @createDate 2012-2-6 下午04:41:48

     * @param targetWidth 目标的宽度

     * @param targetHeight 目标的高度

     * @param standardWidth 标准(指定)宽度

     * @param standardHeight 标准(指定)高度

     * @return 最小的合适比例

     */

    public static double getScaling(double targetWidth, double targetHeight, double standardWidth, double standardHeight) {

        double widthScaling = 0d;

        double heightScaling = 0d;

        if (targetWidth  standardWidth) {

            widthScaling = standardWidth / (targetWidth * 1.00d);

        } else {

            widthScaling = 1d;

        }

        if (targetHeight  standardHeight) {

            heightScaling = standardHeight / (targetHeight * 1.00d);

        } else {

            heightScaling = 1d;

        }

        return Math.min(widthScaling, heightScaling);

    }

如何用java为文件生成缩略图

public static boolean scale(String imagepath,String newpath){

// 返回一个 BufferedImage,作为使用从当前已注册 ImageReader 中自动选择的 ImageReader 解码所提供 File 的结果

BufferedImage image=null;

try {

image = ImageIO.read(new File(imagepath));

} catch (IOException e) {

System.out.println("读取图片文件出错!"+e.getMessage());

return false;

}

// Image Itemp = image.getScaledInstance(300, 300, image.SCALE_SMOOTH);

double Ratio = 0.0;

if ((image.getHeight() 300) ||(image.getWidth() 300)) {

if (image.getHeight() image.getWidth())

//图片要缩放的比例

Ratio = 300.0 / image.getHeight();

else

Ratio = 300.0 / image.getWidth();

}

// 根据仿射转换和插值类型构造一个 AffineTransformOp。

AffineTransformOp op = new AffineTransformOp(AffineTransform

.getScaleInstance(Ratio, Ratio), null);

// 转换源 BufferedImage 并将结果存储在目标 BufferedImage 中。

image = op.filter(image,null);

//image.getScaledInstance(300,300,image.SCALE_SMOOTH);

FileOutputStream out=null;

try {

out = new FileOutputStream(newpath);

ImageIO.write((BufferedImage)image,"bmp",out);

out.close();

} catch (Exception e) {

System.out.println("写图片文件出错!!"+e.getMessage());

return false;

}

return true;

}

java实现缩略图的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java 缩放图片、java实现缩略图的信息别忘了在本站进行查找喔。

The End

发布于:2022-12-07,除非注明,否则均为首码项目网原创文章,转载请注明出处。