在实现pirntSCU时,需要将dicom图像转为灰度图像,使用以下代码进行转换时,预览的图像发生了偏移,使用类库dcm4che3,如何解决偏移问题,代码如下:
public static byte[] convertToGreyImage(File imgFile) throws IOException {
DicomInputStream dicomInputStream = new DicomInputStream(imgFile);
// Attributes attrs = dicomInputStream.readDataset();
ImageInputStream imageInputStream = ImageIO.createImageInputStream(dicomInputStream);
// 获取DICOM图像读取器
Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByFormatName("DICOM");
ImageReader imageReader = imageReaders.next();
// DICOM图像读取参数
DicomImageReadParam dicomReadParam = (DicomImageReadParam) imageReader.getDefaultReadParam();
dicomReadParam.setWindowCenter(40); // DICOM窗位
dicomReadParam.setWindowWidth(400); // DICOM窗宽
//自动计算窗位窗宽
dicomReadParam.setAutoWindowing(true);
// dicomReadParam.setPresentationState(attrs);
dicomReadParam.setDestinationType(ImageTypeSpecifier.createGrayscale(8, DataBuffer.TYPE_BYTE,false));
// 设置图像读取器的输入流
imageReader.setInput(imageInputStream, false);
// 读取DICOM图像
BufferedImage dicomImage = imageReader.read(0, dicomReadParam);
//获取图像偏移信息
int offsetX = dicomImage.getMinX();
int offsetY = dicomImage.getMinY();
// 将DICOM图像转换为灰度图像
BufferedImage greyImage = new BufferedImage(dicomImage.getWidth(), dicomImage.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
Graphics2D graphics = greyImage.createGraphics();
graphics.drawImage(dicomImage, -offsetX, -offsetY, null);
graphics.dispose();
// 获取TIFF ImageWriter
ImageWriter writer = ImageIO.getImageWritersByFormatName("TIF").next();
// 设置压缩参数(可选)
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_DEFAULT);
// 将灰度图像转换为字节数组
// 将图像写入 ByteArrayOutputStream
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageOutputStream ios = ImageIO.createImageOutputStream(outputStream);
writer.setOutput(ios);
writer.write(null, new javax.imageio.IIOImage(greyImage, null, null), param);
ios.close();
// ImageIO.write(greyImage, "TIFF", outputStream);
byte[] greyBytes = outputStream.toByteArray();
// 关闭流
dicomInputStream.close();
imageInputStream.close();
outputStream.close();
return greyBytes;
}
最终预览的效果如下: