
正文
java代码实现图像平滑 java代码实现图像平滑功能
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
怎么用java代码放大或缩小图片不失真。
放大图像不会导致失真,而缩小图像将不可避免的失真。
Java中也同样是这样。
但java提供了4个缩放的微调选项。
image.SCALE_SMOOTH //平滑优先
image.SCALE_FAST//速度优先
image.SCALE_AREA_AVERAGING //区域均值
image.SCALE_REPLICATE //像素复制型缩放
image.SCALE_DEFAULT //默认缩放模式
调用方法
Image new_img=old_img.getScaledInstance(1024, 768, Image.SCALE_SMOOTH);
得到一张缩放后的新图。
相关问答
Q1: java数字图像处理常用算法
前些时候做毕业设计 用java做的数字图像处理方面的东西 这方面的资料ms比较少 发点东西上来大家共享一下 主要就是些算法 有自己写的 有人家的 还有改人家的 有的算法写的不好 大家不要见笑
一 读取bmp图片数据
// 获取待检测图像 数据保存在数组 nData[] nB[] nG[] nR[]中
public void getBMPImage(String source) throws Exception { clearNData(); //清除数据保存区 FileInputStream fs = null; try { fs = new FileInputStream(source); int bfLen = ; byte bf[] = new byte[bfLen]; fs read(bf bfLen); // 读取 字节BMP文件头 int biLen = ; byte bi[] = new byte[biLen]; fs read(bi biLen); // 读取 字节BMP信息头
// 源图宽度 nWidth = (((int) bi[ ] xff) ) | (((int) bi[ ] xff) ) | (((int) bi[ ] xff) ) | (int) bi[ ] xff;
// 源图高度 nHeight = (((int) bi[ ] xff) ) | (((int) bi[ ] xff) ) | (((int) bi[ ] xff) ) | (int) bi[ ] xff;
// 位数 nBitCount = (((int) bi[ ] xff) ) | (int) bi[ ] xff;
// 源图大小 int nSizeImage = (((int) bi[ ] xff) ) | (((int) bi[ ] xff) ) | (((int) bi[ ] xff) ) | (int) bi[ ] xff;
// 对 位BMP进行解析 if (nBitCount == ){ int nPad = (nSizeImage / nHeight) nWidth * ; nData = new int[nHeight * nWidth]; nB=new int[nHeight * nWidth]; nR=new int[nHeight * nWidth]; nG=new int[nHeight * nWidth]; byte bRGB[] = new byte[(nWidth + nPad) * * nHeight]; fs read(bRGB (nWidth + nPad) * * nHeight); int nIndex = ; for (int j = ; j nHeight; j++){ for (int i = ; i nWidth; i++) { nData[nWidth * (nHeight j ) + i] = ( xff) | (((int) bRGB[nIndex + ] xff) ) | (((int) bRGB[nIndex + ] xff) ) | (int) bRGB[nIndex] xff; nB[nWidth * (nHeight j ) + i]=(int) bRGB[nIndex] xff; nG[nWidth * (nHeight j ) + i]=(int) bRGB[nIndex+ ] xff; nR[nWidth * (nHeight j ) + i]=(int) bRGB[nIndex+ ] xff; nIndex += ; } nIndex += nPad; } // Toolkit kit = Toolkit getDefaultToolkit(); // image = kit createImage(new MemoryImageSource(nWidth nHeight // nData nWidth));
/* //调试数据的读取
FileWriter fw = new FileWriter( C:\\Documents and Settings\\Administrator\\My Documents\\nDataRaw txt );//创建新文件 PrintWriter out = new PrintWriter(fw); for(int j= ;jnHeight;j++){ for(int i= ;inWidth;i++){ out print(( * +nData[nWidth * (nHeight j ) + i])+ _ +nR[nWidth * (nHeight j ) + i]+ _ +nG[nWidth * (nHeight j ) + i]+ _ +nB[nWidth * (nHeight j ) + i]+ ); } out println( ); } out close();*/ } } catch (Exception e) { e printStackTrace(); throw new Exception(e); } finally { if (fs != null) { fs close(); } } // return image; }
二 由r g b 获取灰度数组
public int[] getBrightnessData(int rData[] int gData[] int bData[]){ int brightnessData[]=new int[rData length]; if(rData length!=gData length || rData length!=bData length || bData length!=gData length){ return brightnessData; } else { for(int i= ;ibData length;i++){ double temp= *rData[i]+ *gData[i]+ *bData[i]; brightnessData[i]=(int)(temp)+((temp (int)(temp)) ? : ); } return brightnessData; } }
三 直方图均衡化
public int [] equilibrateGray(int[] PixelsGray int width int height) { int gray; int length=PixelsGray length; int FrequenceGray[]=new int[length]; int SumGray[]=new int[ ]; int ImageDestination[]=new int[length]; for(int i = ; i length ;i++) { gray=PixelsGray[i]; FrequenceGray[gray]++; } // 灰度均衡化 SumGray[ ]=FrequenceGray[ ]; for(int i= ;i ;i++){ SumGray[i]=SumGray[i ]+FrequenceGray[i]; } for(int i= ;i ;i++) { SumGray[i]=(int)(SumGray[i]* /length); } for(int i= ;iheight;i++) { for(int j= ;jwidth;j++) { int k=i*width+j; ImageDestination[k]= xFF | ((SumGray[PixelsGray[k]] ) | (SumGray[PixelsGray[k]] ) | SumGray[PixelsGray[k]]); } } return ImageDestination; }
四 laplace 阶滤波 增强边缘 图像锐化
public int[] laplace DFileter(int []data int width int height){ int filterData[]=new int[data length]; int min= ; int max= ; for(int i= ;iheight;i++){ for(int j= ;jwidth;j++){ if(i== || i==height || j== || j==width ) filterData[i*width+j]=data[i*width+j]; else filterData[i*width+j]= *data[i*width+j] data[i*width+j ] data[i*width+j+ ] data[(i )*width+j] data[(i )*width+j ] data[(i )*width+j+ ] data[(i+ )*width+j] data[(i+ )*width+j ] data[(i+ )*width+j+ ]; if(filterData[i*width+j]min) min=filterData[i*width+j]; if(filterData[i*width+j]max) max=filterData[i*width+j]; } }// System out println( max: +max);// System out println( min: +min); for(int i= ;iwidth*height;i++){ filterData[i]=(filterData[i] min)* /(max min); } return filterData; }
五 laplace 阶增强滤波 增强边缘 增强系数delt
public int[] laplaceHigh DFileter(int []data int width int height double delt){ int filterData[]=new int[data length]; int min= ; int max= ; for(int i= ;iheight;i++){ for(int j= ;jwidth;j++){ if(i== || i==height || j== || j==width ) filterData[i*width+j]=(int)(( +delt)*data[i*width+j]); else filterData[i*width+j]=(int)(( +delt)*data[i*width+j] data[i*width+j ]) data[i*width+j+ ] data[(i )*width+j] data[(i )*width+j ] data[(i )*width+j+ ] data[(i+ )*width+j] data[(i+ )*width+j ] data[(i+ )*width+j+ ]; if(filterData[i*width+j]min) min=filterData[i*width+j]; if(filterData[i*width+j]max) max=filterData[i*width+j]; } } for(int i= ;iwidth*height;i++){ filterData[i]=(filterData[i] min)* /(max min); } return filterData; } 六 局部阈值处理 值化
// 局部阈值处理 值化 niblack s method /*原理 T(x y)=m(x y) + k*s(x y) 取一个宽度为w的矩形框 (x y)为这个框的中心 统计框内数据 T(x y)为阈值 m(x y)为均值 s(x y)为均方差 k为参数(推荐 )计算出t再对(x y)进行切割 / 这个算法的优点是 速度快 效果好 缺点是 niblack s method会产生一定的噪声 */ public int[] localThresholdProcess(int []data int width int height int w int h double coefficients double gate){ int[] processData=new int[data length]; for(int i= ;idata length;i++){ processData[i]= ; } if(data length!=width*height) return processData; int wNum=width/w; int hNum=height/h; int delt[]=new int[w*h]; //System out println( w; +w+ h: +h+ wNum: +wNum+ hNum: +hNum); for(int j= ;jhNum;j++){ for(int i= ;iwNum;i++){ //for(int j= ;j ;j++){ // for(int i= ;i ;i++){ for(int n= ;nh;n++) for(int k= ;kw;k++){ delt[n*w+k]=data[(j*h+n)*width+i*w+k]; //System out print( delt[ +(n*w+k)+ ]: +delt[n*w+k]+ ); } //System out println(); /* for(int n= ;nh;n++) for(int k= ;kw;k++){ System out print( data[ +((j*h+n)*width+i*w+k)+ ]: +data[(j*h+n)*width+i*w+k]+ ); } System out println(); */ delt=thresholdProcess(delt w h coefficients gate); for(int n= ;nh;n++) for(int k= ;kw;k++){ processData[(j*h+n)*width+i*w+k]=delt[n*w+k]; // System out print( delt[ +(n*w+k)+ ]: +delt[n*w+k]+ ); } //System out println(); /* for(int n= ;nh;n++) for(int k= ;kw;k++){ System out print( processData[ +((j*h+n)*width+i*w+k)+ ]: +processData[(j*h+n)*width+i*w+k]+ ); } System out println(); */ } } return processData; }
七 全局阈值处理 值化
public int[] thresholdProcess(int []data int width int height double coefficients double gate){ int [] processData=new int[data length]; if(data length!=width*height) return processData; else{ double sum= ; double average= ; double variance= ; double threshold; if( gate!= ){ threshold=gate; } else{ for(int i= ;iwidth*height;i++){ sum+=data[i]; } average=sum/(width*height); for(int i= ;iwidth*height;i++){ variance+=(data[i] average)*(data[i] average); } variance=Math sqrt(variance); threshold=average coefficients*variance; } for(int i= ;iwidth*height;i++){ if(data[i]threshold) processData[i]= ; else processData[i]= ; } return processData; } }
八 垂直边缘检测 sobel算子
public int[] verticleEdgeCheck(int []data int width int height int sobelCoefficients) throws Exception{ int filterData[]=new int[data length]; int min= ; int max= ; if(data length!=width*height) return filterData; try{ for(int i= ;iheight;i++){ for(int j= ;jwidth;j++){ if(i== || i== || i==height || i==height ||j== || j== || j==width || j==width ){ filterData[i*width+j]=data[i*width+j]; } else{ double average; //中心的九个像素点 //average=data[i*width+j] Math sqrt( )*data[i*width+j ]+Math sqrt( )*data[i*width+j+ ] average=data[i*width+j] sobelCoefficients*data[i*width+j ]+sobelCoefficients*data[i*width+j+ ] data[(i )*width+j ]+data[(i )*width+j+ ] data[(i+ )*width+j ]+data[(i+ )*width+j+ ]; filterData[i*width+j]=(int)(average); } if(filterData[i*width+j]min) min=filterData[i*width+j]; if(filterData[i*width+j]max) max=filterData[i*width+j]; } } for(int i= ;iwidth*height;i++){ filterData[i]=(filterData[i] min)* /(max min); } } catch (Exception e) { e printStackTrace(); throw new Exception(e); } return filterData; }
九 图像平滑 * 掩模处理(平均处理) 降低噪声
lishixinzhi/Article/program/Java/hx/201311/26286
Q2: 如何在Java中进行图片剪裁 疯狂JAVA
package test;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.Buffer;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
/**
* 裁剪、缩放图片工具类
*
* @author CSDN 没有梦想-何必远方
*/
public class ImgUtils {
/**
* 缩放图片方法
*
* @param srcImageFile
* 要缩放的图片路径
* @param result
* 缩放后的图片路径
* @param height
* 目标高度像素
* @param width
* 目标宽度像素
* @param bb
* 是否补白
*/
public final static void scale(String srcImageFile, String result,
int height, int width, boolean bb) {
try {
double ratio = 0.0; // 缩放比例
File f = new File(srcImageFile);
BufferedImage bi = ImageIO.read(f);
Image itemp = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH);// bi.SCALE_SMOOTH
// 选择图像平滑度比缩放速度具有更高优先级的图像缩放算法。
// 计算比例
if ((bi.getHeight() height) || (bi.getWidth() width)) {
double ratioHeight = (new Integer(height)).doubleValue()
/ bi.getHeight();
double ratioWhidth = (new Integer(width)).doubleValue()
/ bi.getWidth();
if (ratioHeight ratioWhidth) {
ratio = ratioHeight;
} else {
ratio = ratioWhidth;
}
AffineTransformOp op = new AffineTransformOp(AffineTransform// 仿射转换
.getScaleInstance(ratio, ratio), null);// 返回表示剪切变换的变换
itemp = op.filter(bi, null);// 转换源 BufferedImage 并将结果存储在目标
// BufferedImage 中。
}
if (bb) {// 补白
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);// 构造一个类型为预定义图像类型之一的
// BufferedImage。
Graphics2D g = image.createGraphics();// 创建一个
// Graphics2D,可以将它绘制到此
// BufferedImage 中。
g.setColor(Color.white);// 控制颜色
g.fillRect(0, 0, width, height);// 使用 Graphics2D 上下文的设置,填充 Shape
// 的内部区域。
if (width == itemp.getWidth(null))
g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2,
itemp.getWidth(null), itemp.getHeight(null),
Color.white, null);
else
g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0,
itemp.getWidth(null), itemp.getHeight(null),
Color.white, null);
g.dispose();
itemp = image;
}
ImageIO.write((BufferedImage) itemp, "JPEG", new File(result)); // 输出压缩图片
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 裁剪图片方法
*
* @param bufferedImage
* 图像源
* @param startX
* 裁剪开始x坐标
* @param startY
* 裁剪开始y坐标
* @param endX
* 裁剪结束x坐标
* @param endY
* 裁剪结束y坐标
* @return
*/
public static BufferedImage cropImage(BufferedImage bufferedImage,
int startX, int startY, int endX, int endY) {
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
if (startX == -1) {
startX = 0;
}
if (startY == -1) {
startY = 0;
}
if (endX == -1) {
endX = width - 1;
}
if (endY == -1) {
endY = height - 1;
}
BufferedImage result = new BufferedImage(endX - startX, endY - startY,
4);
for (int x = startX; x endX; ++x) {
for (int y = startY; y endY; ++y) {
int rgb = bufferedImage.getRGB(x, y);
result.setRGB(x - startX, y - startY, rgb);
}
}
return result;
}
public static void main(String[] args) throws IOException {
File input = new File("input.jpg");
BufferedImage img = ImageIO.read(input);
cropImage(img, 10, 10, 20, 20);
File output = new File("output.jpg");
ImageIO.write(img, "jpg", output);
}
}
Q3: java里面获得图像像素后怎么做dct变换
private void setAlpha(ByteArrayOutputStream os) {
try {
ImageIcon imageIcon = new ImageIcon(os.toByteArray());
BufferedImage bufferedImage = new BufferedImage(imageIcon.getIconWidth(),imageIcon.getIconHeight()
, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();
g2D.drawImage(imageIcon.getImage(), 0, 0,
imageIcon.getImageObserver());
//循环每一个像素点,改变像素点的Alpha值
int alpha = 100;
for (int j1 = bufferedImage.getMinY(); j1 bufferedImage.getHeight(); j1++) {
for (int j2 = bufferedImage.getMinX(); j2 bufferedImage.getWidth(); j2++) {
int rgb = bufferedImage.getRGB(j2, j1);
rgb = ( (alpha + 1) 24) | (rgb 0x00ffffff);
bufferedImage.setRGB(j2, j1, rgb);
}
}
g2D.drawImage(bufferedImage, 0, 0, imageIcon.getImageObserver());
//生成图片为PNG
ImageIO.write(bufferedImage, "png", new File(图片路径));
}
catch (Exception e) {
e.printStackTrace();
}
}
使用JAVA对图片进行效果变换(第二幅图覆盖第一幅图的像素并显示)
一提到JAVA,谈论最多的就是JSP/SERVLET/J2EE之类的,但对于用JAVA对图片进行效果变换,到论坛里看了看,关于这方面的话题并不多,网上关于图像效果处理的文章也并不丰富,于是在自己摸索了几天,并且参考了AnfyJava(专业级的JAVA效果生成器)后,我用轻量级控件写了一个(AnfyJava继承的是Applet,Applet是java.awt包中的,属于重量级控件,SUN现在推荐使用swing来编写图形程序,因此,我用的是JApplet)。
其实,用JAVA做图像效果和其它语言在本质上并没有什么区别,只不过在实现起来有所不同罢了,下面我就把我在项目中处理的经验与大家分享一下吧。
图像的变换,实际上就是把两幅图片的内容进行某些运算,生成新的图像,然后显示出来,最终实现从一幅图片到另一幅图片的过度效果。变换的具体过程如下:
在上面的过程中,图片A和B的尺寸最好保持一致,如果不一致的话,可能要做一些额外的处理,在此,我选用的图片A和B的尺寸是一致的。
首先,我们将其当作一个Applet来写,由于Applet的局限性,不可以直接使用File类来读取图像文件,因此,我们只能通过如下方法来获取图像文件。
URLClassLoader urlLoader = (URLClassLoader)this.getClass().getClassLoader();
URL url = urlLoader.findResource("imagea.gif");
Image image = Toolkit.getDefaultToolkit().getImage(url);
当我们获得了图像后,可以通过java.awt.image.PixelGrabber包中的PixelGrabber方法来将图像中的像素信息完全读取出来,其用法如下:
PixelGrabber(Image img, int x, int y, int w, int h, int[] pix, int off, int scansize)
其中img是要读取的图像,x/y是要读取图像中的左上角坐标,w/h分别是从x/y开始起的距离,其实x,y,w,h就是一个矩形,pix是保存像素的数组,off是读取图像时开始的位置,scansize是指扫描的宽度,一般来说和w相等。
int width = image.getWidth();
int height = image.getHeight();
int size = width * height;
int[] pixels = new int[size];
pixelgrabber = new PixelGrabber(image, 0, 0, width, height, pixels, 0, width);
try {
pixelgrabber.grabPixels(); //读取像素入数组
}
catch (InterruptedException _ex) {}
由于像素信息是由alpha,red,green,blue组成的,其格式为
因此,我们可以将颜色分解成单独的RGB信息
int alpha = (pixel 24) 0xff;
int red = (pixel 16) 0xff;
int green = (pixel 8) 0xff;
int blue = (pixel) 0xff;
假如要实现显示图片A后,图片B由上至下展开,则可以每次将图片A中的一行像素替换为B中的相应行,然后生成新的像素信息:
图像A的像素数组 图像B的像素数组
old = pixelA; //保存图片A的像素信息
oldR = redA; //保存图片A的R信息
oldG = greenA; //保存图片A的G信息
oldB = blueA; //保存图片A的B信息
for (int i = 0; i width; i++) {//line为行数
oldR[line * width + i] = redA [line * width + i];
oldG[line * width + i] = greenA [line * width + i];
oldB[line * width + i] = blueA [line * width + i];
old[line * width + i] = oldR[line * width + i] 16 + oldG[line * width + i] 8 + oldB[line * width + i];
}
当生成新的像素信息后,可以通过java.awt.image.MemoryImageSource包中的MemoryImageSource(int w, int h, ColorModel cm, int[] pix, int off, int scan)方法将像素数组对应到图像,并且可以用newPixels()方法来生成新的图像(具体用法可以参考JAVA API DOC)。
memoryimagesource = new MemoryImageSource(imageWidth, imageHeight,
new DirectColorModel(24, 0xff0000, 0x00ff00, 0x0000ff), blocks, 0, imageWidth);
//检查java版本
String javaVersion;
try {
javaVersion = System.getProperty("java.version");
}
catch (SecurityException _ex) {
javaVersion = "unk";
}
if (!javaVersion.startsWith("1.0")) { //jdk1.1以上的版本才支持此方法
try {
memoryimagesource.setAnimated(true);
memoryimagesource.setFullBufferUpdates(true);
imageBuf = createImage(memoryimagesource);
memoryimagesource.newPixels();//生成新的图像
}
catch (NoSuchMethodError _ex) {
System.out.println("unknow java version!");
}
}
到此,新的图像已经产生,只需要输出到屏幕即可。
在此,需要注意以下几个问题:
1、由于Applet读取的图像文件可以比较大,对于速度较慢的网络,可能会造成图像未读取完全就开始进行变换,因此,建议使用MediaTracker方法来保证图像能被顺利载入。
2、 在显示的时候,为了避免闪烁,可以采用双缓冲的方法。
3、 由于在某此高速计算机上,生成新的像素可以非常快,为了避免速度过快而造成效果并不明显,可以加以适当的延时处理。
4、 为了保证效果的平滑,我们特地开辟了非常大的数组来保存像素/RGB信息,这是以空间换时间的做法。
完整的源程序附下(在jdk1.4/2k Server/RedHat9下运行通过,所用机器为P4 2.4G/512M)
package pic;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
public class effect
extends JApplet
implements Runnable {
//定义变量
Toolkit toolkit;
int totalBlocks = 0; //图像被分解成的块数,默认为 宽X高
int[] blocks; //保存块数的信息
Image[] bufferImage = new Image[2]; //屏幕上的图形缓冲
VolatileImage offScreenImage;
Image imageBuf; //保存图片缓冲区内容
Graphics2D offScreenGraphics;
Thread thread;
MediaTracker mediaTracker;
boolean[] isImageReady; //图片是否已经装载
MemoryImageSource memoryimagesource;
int imageWidth, imageHeight; //图像的宽及高
int[] pixelA, pixelB;
int[] redA, greenA, blueA, redB, greenB, blueB;
public effect() throws HeadlessException {
bufferImage[0] = getImage("a.jpg");
bufferImage[1] = getImage("b.jpg");
if ( (bufferImage[0].getWidth(this) != bufferImage[1].getWidth(this)) ||
(bufferImage[0].getHeight(this) != bufferImage[1].getHeight(this))) {
System.out.println("图像尺寸不一致!");
return;
}
toolkit = getToolkit();
imageWidth = bufferImage[0].getWidth(this);
imageHeight = bufferImage[0].getHeight(this);
totalBlocks = imageWidth * imageHeight; //计算分解的块数
blocks = new int[totalBlocks];
pixelA = new int[totalBlocks];
pixelB = new int[totalBlocks];
redA = new int[totalBlocks];
greenA = new int[totalBlocks];
blueA = new int[totalBlocks];
redB = new int[totalBlocks];
greenB = new int[totalBlocks];
blueB = new int[totalBlocks];
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
offScreenImage = gc.createCompatibleVolatileImage(imageWidth, imageHeight); //创建图像缓冲
offScreenGraphics = offScreenImage.createGraphics(); //取得缓冲的graphics对象
}
public void init() {
getImagePixels(bufferImage[0], pixelA);
getImagePixels(bufferImage[1], pixelB);
for (int i = 0; i totalBlocks; i++) {
blocks[i] = pixelA[i]; //保存图像A的像素信息
redA[i] = pixelA[i] 0xff0000; //保存图像B的red值
greenA[i] = pixelA[i] 0x00ff00; //保存图像B的green值
blueA[i] = pixelA[i] 0x0000ff; //保存图像B的blue值
redB[i] = pixelB[i] 0xff0000; //保存图像B的red值
greenB[i] = pixelB[i] 0x00ff00; //保存图像B的green值
blueB[i] = pixelB[i] 0x0000ff; //保存图像B的blue值
}
prepareImagePixels(); //将像素信息还原为图像
}
public void run() {
//检查java版本
String javaVersion;
try {
javaVersion = System.getProperty("java.version");
}
catch (SecurityException _ex) {
javaVersion = "unk";
}
if (javaVersion.startsWith("1.0")) {
System.out.println("require java 1.1 or later version!");
return;
}
try { //暂停3秒钟后等待效果开始
thread.sleep(3000l);
}
catch (InterruptedException ex1) {
}
int line = 0;
Thread currentThread = Thread.currentThread();
while (line imageHeight thread == currentThread) {
for (int i = 0; i imageWidth; i++) {
int offset = line * imageWidth + i;
blocks[offset] = pixelB[offset]; //与下一被注释的语句作用相同
//blocks[offset] = redB[offset] | greenB[offset] | blueB[offset];
}
memoryimagesource.newPixels(); //生成新的图像
line++;
repaint();
//适当延时
try {
thread.sleep(20l);
}
catch (InterruptedException ex) {
}
}
}
public void paint(Graphics g) {
if (offScreenGraphics != null) { //保证在destory()时不引发异常
offScreenGraphics.drawImage(imageBuf, 0, 0, this);
g.drawImage(offScreenImage, 0, 0, this);
}
}
public void start() {
if (thread == null) {
thread = new Thread(this);
thread.start();
}
}
public void stop() {
thread = null;
}
public final void update(Graphics g) {
paint(g);
}
public void destroy() {
if (offScreenImage != null) {
offScreenImage.flush();
}
offScreenImage = null;
if (offScreenGraphics != null) {
offScreenGraphics.dispose();
}
offScreenGraphics = null;
System.gc();
}
Image getImage(String filename) {
URLClassLoader urlLoader = (URLClassLoader)this.getClass().getClassLoader();
URL url = null;
Image image = null;
url = urlLoader.findResource(filename);
image = Toolkit.getDefaultToolkit().getImage(url);
MediaTracker mediatracker = new MediaTracker(this);
try {
mediatracker.addImage(image, 0);
mediatracker.waitForID(0);
}
catch (InterruptedException _ex) {
image = null;
}
if (mediatracker.isErrorID(0)) {
image = null;
}
return image;
}
private boolean getImagePixels(Image image, int pixels[]) {
PixelGrabber pixelgrabber = new PixelGrabber(image, 0, 0, imageWidth,
imageHeight, pixels,
0, imageWidth);
try {
pixelgrabber.grabPixels();
}
catch (InterruptedException _ex) {
return false;
}
return true;
}
void prepareImagePixels() {
memoryimagesource = new MemoryImageSource(imageWidth, imageHeight,
new DirectColorModel(24, 0xff0000,
0x00ff00, 0x0000ff), blocks, 0, imageWidth);
try {
memoryimagesource.setAnimated(true);
memoryimagesource.setFullBufferUpdates(true);
imageBuf = createImage(memoryimagesource);
memoryimagesource.newPixels(); //生成新的图像
}
catch (NoSuchMethodError _ex) {
}
}
public int getWidth() {
return imageWidth;
}
public int getHeight() {
return imageHeight;
}
public static void main(String args[]) {
JFrame frame = new JFrame("Demo");
effect e = new effect();
e.init();
e.start();
frame.getContentPane().setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.getContentPane().add(e);
frame.setSize(new Dimension(e.getWidth() + 6, e.getHeight() + 20));
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = frame.getSize();
frame.setLocation( (screenSize.width - frameSize.width) / 2,
(screenSize.height - frameSize.height) / 2);
frame.show();
}
}
新建一个HTML文件,加入以下语句可作为Applet(其中width/height分别是图片的高和宽):
作为应用程序运行的时候,在命令行输入:
java pic.effect
Q4: java如何实现把一个大图片压缩到指定大小的图片且长宽比不变
也就是图片压缩java代码实现图像平滑,可以不修改任何大小的压缩(速度快)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可适用于其java代码实现图像平滑他图片类型的转换
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
out.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
return "ok";
}
关于java代码实现图像平滑和java代码实现图像平滑功能的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。







