use of loci.formats.codec.PackbitsCodec in project bioformats by openmicroscopy.
the class PhotoshopTiffReader method openBytes.
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
@Override
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException {
if (getSeries() == 0)
return super.openBytes(no, buf, x, y, w, h);
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
int offsetIndex = 0;
for (int i = 1; i < getSeries(); i++) {
offsetIndex += core.get(i).sizeC;
}
tag.seek(layerOffset[offsetIndex]);
int bpp = FormatTools.getBytesPerPixel(getPixelType());
if (compression[getSeries() - 1] == PACKBITS || compression[getSeries() - 1] == ZIP) {
Codec codec = compression[getSeries() - 1] == ZIP ? new ZlibCodec() : new PackbitsCodec();
CodecOptions options = new CodecOptions();
options.maxBytes = FormatTools.getPlaneSize(this) / getSizeC();
ByteArrayHandle pix = new ByteArrayHandle();
for (int c = 0; c < getSizeC(); c++) {
int index = channelOrder[getSeries() - 1][c];
tag.seek(layerOffset[offsetIndex + index]);
pix.write(codec.decompress(tag, options));
}
RandomAccessInputStream plane = new RandomAccessInputStream(pix);
plane.seek(0);
readPlane(plane, x, y, w, h, buf);
plane.close();
pix = null;
} else
readPlane(tag, x, y, w, h, buf);
return buf;
}
use of loci.formats.codec.PackbitsCodec in project bioformats by openmicroscopy.
the class PictReader method handlePixmap.
/**
* Handles the unpacking of the image data.
*/
private void handlePixmap(int pixelSize, int compCount) throws FormatException, IOException {
LOGGER.debug("handlePixmap({}, {}, {})", new Object[] { rowBytes, pixelSize, compCount });
int rawLen;
// row raw bytes
byte[] buf;
// row uncompressed data
byte[] uBuf = null;
// row uncompressed data - 16+ bit pixels
int[] uBufI = null;
int bufSize = rowBytes;
int outBufSize = getSizeX();
// used to expand pixel data
byte[] outBuf = null;
boolean compressed = (rowBytes >= 8) || (pixelSize == 32);
switch(pixelSize) {
case 32:
if (!compressed)
uBufI = new int[getSizeX()];
else
uBuf = new byte[bufSize];
break;
case 16:
uBufI = new int[getSizeX()];
break;
case 8:
uBuf = new byte[bufSize];
break;
default:
outBuf = new byte[outBufSize];
uBuf = new byte[bufSize];
break;
}
if (!compressed) {
LOGGER.debug("Pixel data is uncompressed (pixelSize={}).", pixelSize);
buf = new byte[bufSize];
for (int row = 0; row < getSizeY(); row++) {
in.read(buf, 0, rowBytes);
switch(pixelSize) {
case 16:
for (int i = 0; i < getSizeX(); i++) {
uBufI[i] = DataTools.bytesToShort(buf, i * 2, 2, false);
}
strips.add(uBufI);
buf = null;
core.get(0).sizeC = 3;
break;
case 8:
strips.add(buf);
break;
default:
// pixel size < 8
expandPixels(pixelSize, buf, outBuf, outBuf.length);
strips.add(outBuf);
buf = null;
}
}
} else {
LOGGER.debug("Pixel data is compressed (pixelSize={}; compCount={}).", pixelSize, compCount);
buf = new byte[bufSize + 1 + bufSize / 128];
for (int row = 0; row < getSizeY(); row++) {
if (rowBytes > 250)
rawLen = in.readShort();
else
rawLen = in.read();
if (rawLen > buf.length)
rawLen = buf.length;
if ((in.length() - in.getFilePointer()) <= rawLen) {
rawLen = (int) (in.length() - in.getFilePointer() - 1);
}
if (rawLen < 0) {
rawLen = 0;
in.seek(in.length() - 1);
}
in.read(buf, 0, rawLen);
if (pixelSize == 16) {
uBufI = new int[getSizeX()];
unpackBits(buf, uBufI);
strips.add(uBufI);
core.get(0).sizeC = 3;
} else {
PackbitsCodec c = new PackbitsCodec();
CodecOptions options = new CodecOptions();
options.maxBytes = getSizeX() * 4;
uBuf = c.decompress(buf, options);
}
if (pixelSize < 8) {
expandPixels(pixelSize, uBuf, outBuf, outBuf.length);
strips.add(outBuf);
} else if (pixelSize == 8) {
strips.add(uBuf);
} else if (pixelSize == 24 || pixelSize == 32) {
byte[] newBuf = null;
for (int q = 0; q < compCount; q++) {
int offset = q * getSizeX();
int len = (int) Math.min(getSizeX(), uBuf.length - offset);
newBuf = new byte[getSizeX()];
if (offset < uBuf.length) {
System.arraycopy(uBuf, offset, newBuf, 0, len);
}
strips.add(newBuf);
}
core.get(0).sizeC = 3;
}
}
}
}
use of loci.formats.codec.PackbitsCodec in project bioformats by openmicroscopy.
the class DicomReader method openBytes.
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
@Override
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException {
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
Integer[] keys = fileList.keySet().toArray(new Integer[0]);
Arrays.sort(keys);
if (fileList.size() > 1) {
int fileNumber = 0;
if (fileList.get(keys[getSeries()]).size() > 1) {
fileNumber = no / imagesPerFile;
no = no % imagesPerFile;
}
String file = fileList.get(keys[getSeries()]).get(fileNumber);
helper.setId(file);
return helper.openBytes(no, buf, x, y, w, h);
}
int ec = isIndexed() ? 1 : getSizeC();
int bpp = FormatTools.getBytesPerPixel(getPixelType());
int bytes = getSizeX() * getSizeY() * bpp * ec;
in.seek(offsets[no]);
if (isRLE) {
// plane is compressed using run-length encoding
CodecOptions options = new CodecOptions();
options.maxBytes = getSizeX() * getSizeY();
for (int c = 0; c < ec; c++) {
PackbitsCodec codec = new PackbitsCodec();
byte[] t = null;
if (bpp > 1) {
int plane = bytes / (bpp * ec);
byte[][] tmp = new byte[bpp][];
long start = in.getFilePointer();
for (int i = 0; i < bpp; i++) {
// one or more extra 0 bytes can be inserted between
// the planes, but there isn't a good way to know in advance
// only way to know is to see if decompressing produces the
// correct number of bytes
tmp[i] = codec.decompress(in, options);
if (i > 0 && tmp[i].length > options.maxBytes) {
in.seek(start);
tmp[i] = codec.decompress(in, options);
}
if (no < imagesPerFile - 1 || i < bpp - 1) {
start = in.getFilePointer();
while (in.read() == 0) ;
long end = in.getFilePointer();
in.seek(end - 1);
}
}
t = new byte[bytes / ec];
for (int i = 0; i < plane; i++) {
for (int j = 0; j < bpp; j++) {
int byteIndex = isLittleEndian() ? bpp - j - 1 : j;
if (i < tmp[byteIndex].length) {
t[i * bpp + j] = tmp[byteIndex][i];
}
}
}
} else {
t = codec.decompress(in, options);
if (t.length < (bytes / ec)) {
byte[] tmp = t;
t = new byte[bytes / ec];
System.arraycopy(tmp, 0, t, 0, tmp.length);
}
if (no < imagesPerFile - 1 || c < ec - 1) {
while (in.read() == 0) ;
in.seek(in.getFilePointer() - 1);
}
}
int rowLen = w * bpp;
int srcRowLen = getSizeX() * bpp;
for (int row = 0; row < h; row++) {
int src = (row + y) * srcRowLen + x * bpp;
int dest = (h * c + row) * rowLen;
int len = (int) Math.min(rowLen, t.length - src - 1);
if (len < 0)
break;
System.arraycopy(t, src, buf, dest, len);
}
}
} else if (isJPEG || isJP2K) {
// plane is compressed using JPEG or JPEG-2000
long end = no < offsets.length - 1 ? offsets[no + 1] : in.length();
byte[] b = new byte[(int) (end - in.getFilePointer())];
in.read(b);
if (b[2] != (byte) 0xff) {
byte[] tmp = new byte[b.length + 1];
tmp[0] = b[0];
tmp[1] = b[1];
tmp[2] = (byte) 0xff;
System.arraycopy(b, 2, tmp, 3, b.length - 2);
b = tmp;
}
if ((b[3] & 0xff) >= 0xf0) {
b[3] -= (byte) 0x30;
}
int pt = b.length - 2;
while (pt >= 0 && b[pt] != (byte) 0xff || b[pt + 1] != (byte) 0xd9) {
pt--;
}
if (pt < b.length - 2) {
byte[] tmp = b;
b = new byte[pt + 2];
System.arraycopy(tmp, 0, b, 0, b.length);
}
Codec codec = null;
CodecOptions options = new CodecOptions();
options.littleEndian = isLittleEndian();
options.interleaved = isInterleaved();
if (isJPEG)
codec = new JPEGCodec();
else
codec = new JPEG2000Codec();
b = codec.decompress(b, options);
int rowLen = w * bpp;
int srcRowLen = getSizeX() * bpp;
int srcPlane = getSizeY() * srcRowLen;
for (int c = 0; c < ec; c++) {
for (int row = 0; row < h; row++) {
System.arraycopy(b, c * srcPlane + (row + y) * srcRowLen + x * bpp, buf, h * rowLen * c + row * rowLen, rowLen);
}
}
} else if (isDeflate) {
// TODO
throw new UnsupportedCompressionException("Deflate data is not supported.");
} else {
// plane is not compressed
readPlane(in, x, y, w, h, buf);
}
if (inverted) {
// white -> 255 (or 65535)
if (bpp == 1) {
for (int i = 0; i < buf.length; i++) {
buf[i] = (byte) (255 - buf[i]);
}
} else if (bpp == 2) {
long maxPixelValue = maxPixelRange + (centerPixelValue / 2);
if (maxPixelRange == -1 || centerPixelValue < (maxPixelRange / 2)) {
maxPixelValue = FormatTools.defaultMinMax(getPixelType())[1];
}
boolean little = isLittleEndian();
for (int i = 0; i < buf.length; i += 2) {
short s = DataTools.bytesToShort(buf, i, 2, little);
DataTools.unpackBytes(maxPixelValue - s, buf, i, 2, little);
}
}
}
return buf;
}
use of loci.formats.codec.PackbitsCodec in project bioformats by openmicroscopy.
the class DicomReader method initFile.
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
@Override
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
in = new RandomAccessInputStream(id);
in.order(true);
CoreMetadata m = core.get(0);
// look for companion files
attachCompanionFiles();
helper = new DicomReader();
helper.setGroupFiles(false);
m.littleEndian = true;
location = 0;
isJPEG = false;
isRLE = false;
bigEndianTransferSyntax = false;
oddLocations = false;
inSequence = false;
bitsPerPixel = 0;
elementLength = 0;
vr = 0;
lut = null;
offsets = null;
inverted = false;
// some DICOM files have a 128 byte header followed by a 4 byte identifier
LOGGER.info("Verifying DICOM format");
MetadataLevel level = getMetadataOptions().getMetadataLevel();
in.seek(128);
if (in.readString(4).equals("DICM")) {
if (level != MetadataLevel.MINIMUM) {
// header exists, so we'll read it
in.seek(0);
addSeriesMeta("Header information", in.readString(128));
in.skipBytes(4);
}
location = 128;
} else
in.seek(0);
LOGGER.info("Reading tags");
long baseOffset = 0;
boolean decodingTags = true;
boolean signed = false;
String currentType = "";
while (decodingTags) {
if (in.getFilePointer() + 4 >= in.length()) {
break;
}
LOGGER.debug("Reading tag from {}", in.getFilePointer());
int tag = getNextTag(in);
if (elementLength <= 0)
continue;
oddLocations = (location & 1) != 0;
LOGGER.debug(" tag={} len={} fp=", new Object[] { tag, elementLength, in.getFilePointer() });
String s = null;
switch(tag) {
case TRANSFER_SYNTAX_UID:
// this tag can indicate which compression scheme is used
s = in.readString(elementLength);
addInfo(tag, s);
if (s.startsWith("1.2.840.10008.1.2.4.9"))
isJP2K = true;
else if (s.startsWith("1.2.840.10008.1.2.4"))
isJPEG = true;
else if (s.startsWith("1.2.840.10008.1.2.5"))
isRLE = true;
else if (s.equals("1.2.8.10008.1.2.1.99"))
isDeflate = true;
else if (s.indexOf("1.2.4") > -1 || s.indexOf("1.2.5") > -1) {
throw new UnsupportedCompressionException("Sorry, compression type " + s + " not supported");
}
if (s.indexOf("1.2.840.10008.1.2.2") >= 0) {
bigEndianTransferSyntax = true;
}
break;
case NUMBER_OF_FRAMES:
s = in.readString(elementLength);
addInfo(tag, s);
double frames = Double.parseDouble(s);
if (frames > 1.0)
imagesPerFile = (int) frames;
break;
case SAMPLES_PER_PIXEL:
addInfo(tag, in.readShort());
break;
case PLANAR_CONFIGURATION:
int config = in.readShort();
m.interleaved = config == 0;
addInfo(tag, config);
break;
case ROWS:
int y = in.readShort();
if (y > getSizeY()) {
m.sizeY = y;
}
addInfo(tag, getSizeY());
break;
case COLUMNS:
int x = in.readShort();
if (x > getSizeX()) {
m.sizeX = x;
}
addInfo(tag, getSizeX());
break;
case PHOTOMETRIC_INTERPRETATION:
case PIXEL_SPACING:
case SLICE_SPACING:
case RESCALE_INTERCEPT:
case WINDOW_CENTER:
String winCenter = in.readString(elementLength);
if (winCenter.trim().length() == 0)
centerPixelValue = -1;
else {
try {
centerPixelValue = new Double(winCenter).intValue();
} catch (NumberFormatException e) {
centerPixelValue = -1;
}
}
addInfo(tag, winCenter);
break;
case RESCALE_SLOPE:
addInfo(tag, in.readString(elementLength));
break;
case BITS_ALLOCATED:
if (bitsPerPixel == 0)
bitsPerPixel = in.readShort();
else
in.skipBytes(2);
addInfo(tag, bitsPerPixel);
break;
case PIXEL_REPRESENTATION:
case PIXEL_SIGN:
short ss = in.readShort();
signed = ss == 1;
addInfo(tag, ss);
break;
case 537262910:
case WINDOW_WIDTH:
String t = in.readString(elementLength);
if (t.trim().length() == 0)
maxPixelRange = -1;
else {
try {
maxPixelRange = new Double(t.trim()).intValue();
} catch (NumberFormatException e) {
maxPixelRange = -1;
}
}
addInfo(tag, t);
break;
case PIXEL_DATA:
case ITEM:
case 0xffee000:
if (elementLength != 0) {
baseOffset = in.getFilePointer();
addInfo(tag, location);
decodingTags = false;
} else
addInfo(tag, null);
break;
case 0x7f880010:
if (elementLength != 0) {
baseOffset = location + 4;
decodingTags = false;
}
break;
case 0x7fe00000:
in.skipBytes(elementLength);
break;
case 0:
in.seek(in.getFilePointer() - 4);
break;
case 0x41430:
currentType = getHeaderInfo(tag, s).trim();
break;
case 0x41500:
if (currentType.equals("IMAGE")) {
if (fileList == null) {
fileList = new HashMap<Integer, List<String>>();
}
int seriesIndex = 0;
if (originalInstance != null) {
try {
seriesIndex = Integer.parseInt(originalInstance);
} catch (NumberFormatException e) {
LOGGER.debug("Could not parse instance number: {}", originalInstance);
}
}
if (fileList.get(seriesIndex) == null) {
fileList.put(seriesIndex, new ArrayList<String>());
}
fileList.get(seriesIndex).add(getHeaderInfo(tag, s).trim());
} else {
companionFiles.add(getHeaderInfo(tag, s).trim());
}
currentType = "";
break;
default:
long oldfp = in.getFilePointer();
addInfo(tag, s);
in.seek(oldfp + elementLength);
}
if (in.getFilePointer() >= (in.length() - 4)) {
decodingTags = false;
}
}
if (imagesPerFile == 0)
imagesPerFile = 1;
if (id.endsWith("DICOMDIR")) {
String parent = new Location(currentId).getAbsoluteFile().getParent();
for (int q = 0; q < fileList.size(); q++) {
Integer[] fileKeys = fileList.keySet().toArray(new Integer[0]);
for (int i = 0; i < fileList.get(fileKeys[q]).size(); i++) {
String file = fileList.get(fileKeys[q]).get(i);
file = file.replace('\\', File.separatorChar);
file = file.replaceAll("/", File.separator);
fileList.get(fileKeys[q]).set(i, parent + File.separator + file);
}
}
for (int i = 0; i < companionFiles.size(); i++) {
String file = companionFiles.get(i);
file = file.replace('\\', File.separatorChar);
file = file.replaceAll("/", File.separator);
companionFiles.set(i, parent + File.separator + file);
}
companionFiles.add(new Location(currentId).getAbsolutePath());
initFile(fileList.get(0).get(0));
return;
}
m.bitsPerPixel = bitsPerPixel;
while (bitsPerPixel % 8 != 0) bitsPerPixel++;
if (bitsPerPixel == 24 || bitsPerPixel == 48) {
bitsPerPixel /= 3;
m.bitsPerPixel /= 3;
}
m.pixelType = FormatTools.pixelTypeFromBytes(bitsPerPixel / 8, signed, false);
int bpp = FormatTools.getBytesPerPixel(getPixelType());
int plane = getSizeX() * getSizeY() * (lut == null ? getSizeC() : 1) * bpp;
LOGGER.info("Calculating image offsets");
// calculate the offset to each plane
in.seek(baseOffset - 12);
int len = in.readInt();
if (len >= 0 && len + in.getFilePointer() < in.length()) {
in.skipBytes(len);
int check = in.readShort() & 0xffff;
if (check == 0xfffe) {
baseOffset = in.getFilePointer() + 2;
}
}
offsets = new long[imagesPerFile];
for (int i = 0; i < imagesPerFile; i++) {
if (isRLE) {
if (i == 0)
in.seek(baseOffset);
else {
in.seek(offsets[i - 1]);
CodecOptions options = new CodecOptions();
options.maxBytes = plane / bpp;
for (int q = 0; q < bpp; q++) {
new PackbitsCodec().decompress(in, options);
while (in.read() == 0) ;
in.seek(in.getFilePointer() - 1);
}
}
in.skipBytes(i == 0 ? 64 : 53);
while (in.read() == 0) ;
offsets[i] = in.getFilePointer() - 1;
} else if (isJPEG || isJP2K) {
// scan for next JPEG magic byte sequence
if (i == 0)
offsets[i] = baseOffset;
else
offsets[i] = offsets[i - 1] + 3;
byte secondCheck = isJPEG ? (byte) 0xd8 : (byte) 0x4f;
in.seek(offsets[i]);
byte[] buf = new byte[8192];
int n = in.read(buf);
boolean found = false;
while (!found) {
for (int q = 0; q < n - 2; q++) {
if (buf[q] == (byte) 0xff && buf[q + 1] == secondCheck && buf[q + 2] == (byte) 0xff) {
if (isJPEG || (isJP2K && buf[q + 3] == 0x51)) {
found = true;
offsets[i] = in.getFilePointer() + q - n;
break;
}
}
}
if (!found) {
for (int q = 0; q < 4; q++) {
buf[q] = buf[buf.length + q - 4];
}
n = in.read(buf, 4, buf.length - 4) + 4;
}
}
} else
offsets[i] = baseOffset + plane * i;
}
makeFileList();
LOGGER.info("Populating metadata");
int seriesCount = fileList.size();
Integer[] keys = fileList.keySet().toArray(new Integer[0]);
Arrays.sort(keys);
if (seriesCount > 1) {
core.clear();
}
for (int i = 0; i < seriesCount; i++) {
if (seriesCount == 1) {
CoreMetadata ms = core.get(i);
ms.sizeZ = imagesPerFile * fileList.get(keys[i]).size();
if (ms.sizeC == 0)
ms.sizeC = 1;
ms.rgb = ms.sizeC > 1;
ms.sizeT = 1;
ms.dimensionOrder = "XYCZT";
ms.metadataComplete = true;
ms.falseColor = false;
if (isRLE)
core.get(i).interleaved = false;
ms.imageCount = ms.sizeZ;
} else {
helper.close();
helper.setId(fileList.get(keys[i]).get(0));
CoreMetadata ms = helper.getCoreMetadataList().get(0);
ms.sizeZ *= fileList.get(keys[i]).size();
ms.imageCount = ms.sizeZ;
core.add(ms);
}
}
// The metadata store we're working with.
MetadataStore store = makeFilterMetadata();
MetadataTools.populatePixels(store, this, true);
String stamp = null;
if (date != null && time != null) {
stamp = date + " " + time;
stamp = DateTools.formatDate(stamp, "yyyy.MM.dd HH:mm:ss", ".");
}
if (stamp == null || stamp.trim().equals(""))
stamp = null;
for (int i = 0; i < core.size(); i++) {
if (stamp != null)
store.setImageAcquisitionDate(new Timestamp(stamp), i);
store.setImageName("Series " + i, i);
}
if (level != MetadataLevel.MINIMUM) {
for (int i = 0; i < core.size(); i++) {
store.setImageDescription(imageType, i);
// all physical sizes were stored in mm, so must be converted to um
if (pixelSizeX != null) {
Length x = FormatTools.getPhysicalSizeX(new Double(pixelSizeX), UNITS.MILLIMETER);
if (x != null) {
store.setPixelsPhysicalSizeX(x, i);
}
}
if (pixelSizeY != null) {
Length y = FormatTools.getPhysicalSizeY(new Double(pixelSizeY), UNITS.MILLIMETER);
if (y != null) {
store.setPixelsPhysicalSizeY(y, i);
}
}
if (pixelSizeZ != null) {
Length z = FormatTools.getPhysicalSizeZ(new Double(pixelSizeZ), UNITS.MILLIMETER);
if (z != null) {
store.setPixelsPhysicalSizeZ(z, i);
}
}
for (int p = 0; p < getImageCount(); p++) {
if (p < positionX.size()) {
if (positionX.get(p) != null) {
Length x = new Length(positionX.get(p), UNITS.MM);
if (x != null) {
store.setPlanePositionX(x, 0, p);
}
}
}
if (p < positionY.size()) {
if (positionY.get(p) != null) {
Length y = new Length(positionY.get(p), UNITS.MM);
if (y != null) {
store.setPlanePositionY(y, 0, p);
}
}
}
if (p < positionZ.size()) {
if (positionZ.get(p) != null) {
Length z = new Length(positionZ.get(p), UNITS.MM);
if (z != null) {
store.setPlanePositionZ(z, 0, p);
}
}
}
}
}
}
}
use of loci.formats.codec.PackbitsCodec in project bioformats by openmicroscopy.
the class PSDReader method openBytes.
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
@Override
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException {
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
in.seek(offset);
int bpp = FormatTools.getBytesPerPixel(getPixelType());
int plane = getSizeX() * getSizeY() * bpp;
if (compressed) {
PackbitsCodec codec = new PackbitsCodec();
CodecOptions options = new CodecOptions();
options.maxBytes = getSizeX() * bpp;
byte[] b = null;
int index = 0;
for (int c = 0; c < getSizeC(); c++) {
for (int row = 0; row < getSizeY(); row++) {
if (row < y || row >= y + h) {
in.skipBytes(lens[c][row]);
} else {
b = new byte[lens[c][row]];
in.read(b);
b = codec.decompress(b, options);
System.arraycopy(b, x * bpp, buf, index, w * bpp);
index += w * bpp;
}
}
}
} else {
readPlane(in, x, y, w, h, buf);
}
return buf;
}
Aggregations