java读取tiff格式图像、像素修改以及格式转换
javatiff_0">java读取tiff图像的踩坑总结:
1.环境:spring boot+maven
2.包:imageio ,jai,codec,metadata;
还有⼀个从github上⾯下载的。这⼏个包都不⼤好,等后续补上下载路径。
import javax.imageio.__;
dia.jai.JAI;
import dec.;
import com.github.jaiimageio.impl.plugins.tiff.*;
主要就是这⼏个了,下⾯是接触到的有关代码。
注意:从外部下载的包加载到本地maven仓库需要使⽤cmd打开输⼊
mvn install:install-file -DgroupId=dia -DartifactId=jai_codec -Dversion=1.1.3 -Dpackaging=jar -Dfile=E:\BaiduNetdiskDownload\jai_codec-1.1.3.jar metadata
tiff_15">⾸先:metadata,是tiff图像的元数据,下⾯有两个⽅式。
1.调⽤tiffMetadataReader包,此⽅法⽐较简单,
引⼊的包:
import com.drew.imaging.tiff.TiffMetadataReader;
import com.drew.imaging.tiff.TiffProcessingException;
import adata.Directory;
import adata.Metadata;
import adata.Tag;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
//详细过程:
File file = new File("C:/Users/86156/Desktop/Show.tif");
BufferedImage bufferedImage = ad(file);
String[] image = WriterFileSuffixes();
System.out.println(image);
System.out.println(bufferedImage);
try{
Metadata metadata = adMetadata(file);
//输出元数据信息
System.out.println(metadata);
}catch (tiffProcessingException e){
System.out.println("发⽣进程异常");
System.out.println(e);
}catch (IOException e) {
System.out.println("发⽣读取异常");
}
try{
Metadata metadata = adMetadata(file);
Iterable<Directory> a = Directories();
for(Directory directory : a) {
Iterator<Tag> tag = Tags().iterator();
while (tag.hasNext()) {
System.out.());
}
}
}catch(TiffProcessingException e){
System.out.println("发⽣异常!");
System.out.println(e);
}
System.out.println("执⾏完毕");
如果出现读取时是空值:
执⾏部分结果如下:
包含了tiff图像的长宽和位数即16,这也为后⾯的⼤坑做了铺垫。
含有投影坐标:WGS84;
⽅法⼆:
1
tiff_76">tiff图像向其他类型转换(转换后原本的元数据可能会丢失)
如果要转换其他格式只需要更改
import dec.ImageCodec;
import dec.ImageEncoder;
import dec.JPEGEncodeParam;
dia.jai.JAI;
dia.jai.RenderedOp;
import java.io.*;
/**
* 将 tiff 转换 jpg 格式
* @param filePath
* @return
*/
public static String tiffTuanJPG(String filePath){
String format = filePath.substring(filePath.lastIndexOf(".")+1);
String turnJpgFile = place("tiff", "jpg");
if(format.equals("tiff")){
File fileTiff = new File(turnJpgFile);
ists()){
System.out.println("该tiff⽂件已经转换为 JPG ⽂件:"+turnJpgFile);
return turnJpgFile;
}
RenderedOp rd = ate("fileload", filePath);//读取iff⽂件
OutputStream ops = null;
try {
ops = new FileOutputStream(turnJpgFile);
//⽂件存储输出流
JPEGEncodeParam param = new JPEGEncodeParam();
ImageEncoder image = ateImageEncoder("JPEG", ops, param); //指定输出格式
//解析输出流进⾏输出
ops.close();
System.out.println("tiff转换jpg成功:"+filePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return turnJpgFile;
}
注意:传参时需要写⼊main内
String filePath = "E:/eeee/eee/aod.tiff";
String qq = tiffTuanJPG(filePath);
System.out.println(qq);
1
2
3
⽅法⼆resizebyaspect(,,);
可以重新调整⼤⼩
private static BufferedImage resizebyaspect(BufferedImage img, int height, int width) {
int ori_width = Width();
int ori_height = Height();
float ratio_w = (float)width/ori_width;
float ratio_h = (float)height/ori_height;
int new_width = (ratio_w < ratio_h) ? width : (int)(ratio_h * ori_width);
int new_height = (ratio_h < ratio_w) ? height : (int)(ratio_w * ori_height);
System.out.println(new_width);
System.out.println(new_height);
Image tmp = ScaledInstance(new_width, new_height, Image.SCALE_SMOOTH);
BufferedImage bufferedImage = new BufferedImage(new_width, new_height, BufferedImage.TYPE_BYTE_GRAY);        Graphics2D g2d = ateGraphics();
g2d.drawImage(tmp, 0, 0, null);
g2d.dispose();
System.out.println("转换成功");
return bufferedImage;
}
调⽤:
File input = new File("E:/aod.tiff");
BufferedImage image = ad(input);
BufferedImage resized = resizebyaspect(image,230,238);
File output = new File("E:/挑战杯/市数据/保定/aod.jpg");
ImageIO.write(resized, "jpg", output);
转换后对⽐
tiff_164">3.读取tiff图像的像素值:
获取单个像素点的rgb值
System.out.RGB(155, 88));
jpg转tiff后读取rgb值运⾏结果如下:
-2185377是单个像素点
这个运⾏结果是jpg转换成tiff的读取结果。但转换过后元数据会有所丢失。
所以很是让⼈抓狂,16位的图。
虽然⾄此仍不知该怎么去解决,但是通过此次的⾃我摸索也获得了很多知识,希望此次能够为正处于这个阶段的同志能够少⾛⼀些弯路,另外由衷感谢以上各位提供的开源代码。感谢!dia.jai.JAI;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriter;
import adata.IIOMetadata;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.FileImageOutputStream;
dia.jai.operator.TransposeDescriptor;
import java.derable.ParameterBlock;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
SimpleDateFormat;
import java.util.Hashtable;
import java.util.NoSuchElementException;
import java.util.Vector;
//使⽤java库对tiff⽂件进⾏操作
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.IndexColorModel;
import java.awt.image.MultiPixelPackedSampleModel;
import java.awt.image.RenderedImage;
import java.awt.image.SampleModel;
import java.awt.image.WritableRaster;
import java.io.*;
dia.jai.ColorCube;
dia.jai.ImageLayout;
dia.jai.Interpolation;
dia.jai.KernelJAI;
dia.jai.LookupTableJAI;
import dec.ImageCodec;
import dec.ImageEncoder;
import dec.PNGEncodeParam;
import dec.TIFFEncodeParam;
import dec.TIFFField;
import decimpl.TIFFImageDecoder;
public class tiff {
public static void main(String[] args) throws IOException {
ImageReader reader = null;
FileImageInputStream fis = null;
//C:\Users\86156\Desktop\aod.tiff
//E:\保定/aod.tiff
File file = new File("C:\\Users\\86156\\Desktop\\aod.tiff");
Object[] src = readtiff(file);
if (src == null)
System.out.println("读取失败");
reader = (ImageReader) src[0];
fis = (FileImageInputStream) src[1];
System.out.println(reader);
System.out.println(fis);
long[] dpiData = new long[]{1, 1};
BufferedImage img = loadtiff(file, dpiData);
System.out.ColorModel());
if (img == null)
System.out.println("空值");
//获取图⽚的长宽和最⼩值
int width = Width();
int height = Height();
int minx = MinX();
int miny = MinY();
int rgb[] = new int[width * height];
int a[][]=new Width()][Height()];
/*for (int i = minx; i < Width(); i++) {
for (int j = miny; j < Height(); j++) {
a[i][j] = RGB(i, j);
}
}
for (int i = 0; i < Width(); i++) {
for (int j = 0; j < Height(); j++) {
System.out.print(a[i][j]);
}
System.out.println();
for (int i = minx; i < width; i++) {
for (int j = miny; j < height; j++) {
int pixel = RGB(i, j); // 下⾯三⾏代码将⼀个数字转换为RGB数字
rgb[0] = (pixel & 0xff0000) >> 16;
rgb[1] = (pixel & 0xff00) >> 8;
rgb[2] = (pixel & 0xff);
System.out.print("i=" + i + ",j=" + j + ":(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + ")");
}
System.out.println();
}
System.out.RGB(155, 88));
System.out.println("-----------------------------");
//RGB(0,0,width-1,height-1 , rgb,0,width);
File pfile = new File("E:/挑战杯/市数据/保定/aod_tiff.png");
//boolean b = makeDispPage(file,0,pfile);
//System.out.println(b);
}
//读取tiff⽂件到 ImageReader Object[0]:ImageReader ,Object[1]:FileImageInputStream    private static Object[] readtiff(File tifFile) {
ImageReader reader = null;
FileImageInputStream fis = null;
Object[] res = null;
try {
reader = ImageReadersByFormatName("tiff").next();
fis = new FileImageInputStream(tifFile);
reader.setInput(fis);
res = new Object[]{reader, fis};
} catch (NoSuchElementException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return res;
}
//获取tiff dpi
public static long[] gettiffDPI(ImageReader reader, int index) {
long[] dpi = new long[2];
IIOMetadata meta = null;
try {
meta = ImageMetadata(index);
org.w3c.dom.Node n = AsTree("javax_imageio_1.0");
n = n.getFirstChild();
while (n != null) {
if (n.getNodeName().equals("Dimension")) {
org.w3c.dom.Node n2 = n.getFirstChild();
while (n2 != null) {
if (n2.getNodeName().equals("HorizontalPixelSize")) {
org.w3c.dom.NamedNodeMap nnm = n2.getAttributes();
org.w3c.dom.Node n3 = nnm.item(0);
float hps = Float.NodeValue());
dpi[0] = und(25.4f / hps);
}
if (n2.getNodeName().equals("VerticalPixelSize")) {
org.w3c.dom.NamedNodeMap nnm = n2.getAttributes();
org.w3c.dom.Node n3 = nnm.item(0);
float vps = Float.NodeValue());
dpi[1] = und(25.4f / vps);
}
n2 = n2.getNextSibling();
}
}
n = n.getNextSibling();
} catch (IOException e) {
e.printStackTrace();
}
return dpi;
}
//读取tiff⽂件到 BufferedImage
private static BufferedImage loadtiff(File tifFile, long[] dpiData) {
ImageReader reader = null;
FileImageInputStream fis = null;
BufferedImage res = null;
try {
Object[] src = readtiff(tifFile);
if (src == null) {
return null;
}
reader = (ImageReader) src[0];
fis = (FileImageInputStream) src[1];
if (reader != null) {
int numPages = NumImages(true);
resizedif (numPages > 0) {
long[] dpiArr = gettiffDPI(reader, 0);
dpiData[0] = dpiArr[0];
dpiData[1] = dpiArr[1];
res = ad(0);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
reader.dispose();
}
if (fis != null) {
try {
fis.flush();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return res;
}
/**
* 从tiff⽂件⽣成原始像素⼤⼩tiff⽂件
*
* @param ftiff  源tiff⽂件
* @param decDir tiff⽬标路径,⽬标⽂件将会以0001.tif,置于此路径下    * @return true表⽰成功, false表⽰失败
*/
public static boolean makeSingleTif(File fTiff, File decDir) {
boolean bres = true;
ImageReader reader = null;
FileImageInputStream fis = null;
try {
reader = ImageReadersByFormatName("tiff").next();
fis = new FileImageInputStream(fTiff);
reader.setInput(fis);
int numPages = NumImages(true);
for (int i = 0; i < numPages; i++) {
long[] dpiData = gettiffDPI(reader, i);
BufferedImage bi = ad(i);
File tif = new Path() + File.separator
+ String.format("%1$04d", i + 1) + ".tif");
bres = createtiff(tif, new RenderedImage[]{bi}, dpiData, false);
}
} catch (Exception e) {
e.printStackTrace();
bres = false;
} finally {
if (reader != null) {
reader.dispose();
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。