private int readPeerCount(DataInputStream data) throws IOException { // get the peer list offset int offset = data.readInt(); if (offset == 0) throw new IOException("File not ready for first read"); if (lastOffset != offset) { peers = null; lastOffset = offset; } int peerCount = data.readInt(); // skip to the start of the data if (data.skip(offset - 8) != (offset - 8)) // skip starts from the current position & offset is defined from // start of file throw new IOException("unable to skip to the required position in the file"); int timestamp = data.readInt(); // drop the cached peer list if the file has changed if (timestamp != lastTimestamp) peers = null; lastTimestamp = timestamp; // compare to current time long dateInSeconds = new Date().getTime() / 1000; if (dateInSeconds > (timestamp + maxAge)) throw new IOException("Batman peer file is stale"); return peerCount; }
private void readTrack(DataInputStream dataInputStream, Track track) throws InvalidMidiDataException, IOException { // search for a "MTrk" chunk while (true) { int nMagic = dataInputStream.readInt(); if (nMagic == MidiConstants.TRACK_MAGIC) { break; } int nChunkLength = dataInputStream.readInt(); if (nChunkLength % 2 != 0) { nChunkLength++; } dataInputStream.skip(nChunkLength); } int nTrackChunkLength = dataInputStream.readInt(); long lTicks = 0; long[] alRemainingBytes = new long[1]; alRemainingBytes[0] = nTrackChunkLength; int[] anRunningStatusByte = new int[1]; // indicates no running status in effect anRunningStatusByte[0] = -1; while (alRemainingBytes[0] > 0) { long lDeltaTicks = readVariableLengthQuantity(dataInputStream, alRemainingBytes); // TDebug.out("delta ticks: " + lDeltaTicks); lTicks += lDeltaTicks; MidiEvent event = readEvent(dataInputStream, alRemainingBytes, anRunningStatusByte, lTicks); track.add(event); } }
public static String computeHash(InputStream stream, long length) throws IOException { int chunkSizeForFile = (int) Math.min(HASH_CHUNK_SIZE, length); // buffer that will contain the head and the tail chunk, chunks will overlap if length is // smaller than two chunks byte[] chunkBytes = new byte[(int) Math.min(2 * HASH_CHUNK_SIZE, length)]; DataInputStream in = new DataInputStream(stream); // first chunk in.readFully(chunkBytes, 0, chunkSizeForFile); long position = chunkSizeForFile; long tailChunkPosition = length - chunkSizeForFile; // seek to position of the tail chunk, or not at all if length is smaller than two chunks while (position < tailChunkPosition && (position += in.skip(tailChunkPosition - position)) >= 0) ; // second chunk, or the rest of the data if length is smaller than two chunks in.readFully(chunkBytes, chunkSizeForFile, chunkBytes.length - chunkSizeForFile); long head = computeHashForChunk(ByteBuffer.wrap(chunkBytes, 0, chunkSizeForFile)); long tail = computeHashForChunk( ByteBuffer.wrap(chunkBytes, chunkBytes.length - chunkSizeForFile, chunkSizeForFile)); return String.format("%016x", length + head + tail); }
/** * Get Word meaning by its offset and its meaning size. * * @param offset offset that is get in .idx file. * @param size size that is get in .idx file * @return meaning of word data */ public String getWordData(long offset, long size) { if (!((new java.io.File(strFileName)).exists())) { return "File: " + strFileName + " does not exist"; } String strMeaning = "not found"; DataInputStream dt = null; try { dt = new DataInputStream(new BufferedInputStream(new FileInputStream(strFileName))); dt.skip(offset); byte[] bt = new byte[(int) size]; dt.read(bt, 0, (int) size); strMeaning = new String(bt, "UTF8"); } catch (Exception ex) { Log.e(TAG, "Read file name '" + strFileName + "'", ex); } finally { if (dt != null) { try { dt.close(); } catch (Exception ex) { Log.w(TAG, "Closing DataInputStream", ex); } } } return strMeaning; }
public void skip(DataInputStream dis) throws IOException { defreezeSuperColumn(dis); /* read the number of columns stored */ dis.readInt(); /* read the size of all columns to skip */ int size = dis.readInt(); dis.skip(size); }
Reader(String idxFileName, String idxFileNameLabels) { try { fileName = idxFileName; dis = new DataInputStream(new FileInputStream(new File(idxFileName))); disLabels = new DataInputStream(new FileInputStream(idxFileNameLabels)); dis.skip(4); disLabels.skip(8); setSize = dis.readInt(); dimSize1 = dis.readInt(); dimSize2 = dis.readInt(); test = new int[setSize][dimSize1 * dimSize2]; label = new byte[setSize]; } catch (IOException e) { System.err.println("Error on initializing \"Reader\""); e.printStackTrace(); } }
static void skipOver(DataInputStream in, long p) throws IOException { int errs = 3; while (p > 0) { long sp = in.skip(p); if (sp > 0) p -= sp; else if (sp == 0) { if (errs <= 0) throw new IOException("Skip returned zero too many times."); errs--; } else throw new IOException("Skip returned negative."); } }
/* * Deserialize a particular column since the name is in the form of * superColumn:column. */ public IColumn deserialize(DataInputStream dis, String name, IFilter filter) throws IOException { if (dis.available() == 0) return null; String[] names = RowMutation.getColumnAndColumnFamily(name); if (names.length == 1) { IColumn superColumn = defreezeSuperColumn(dis); if (name.equals(superColumn.name())) { if (!superColumn.isMarkedForDelete()) { /* read the number of columns stored */ int size = dis.readInt(); /* read the size of all columns */ dis.readInt(); IColumn column = null; for (int i = 0; i < size; ++i) { column = Column.serializer().deserialize(dis, filter); if (column != null) { superColumn.addColumn(column.name(), column); column = null; if (filter.isDone()) { break; } } } } return superColumn; } else { /* read the number of columns stored */ dis.readInt(); /* read the size of all columns to skip */ int size = dis.readInt(); dis.skip(size); return null; } } SuperColumn superColumn = defreezeSuperColumn(dis); if (!superColumn.isMarkedForDelete()) { int size = dis.readInt(); /* skip the size of the columns */ dis.readInt(); if (size > 0) { for (int i = 0; i < size; ++i) { IColumn subColumn = Column.serializer().deserialize(dis, names[1], filter); if (subColumn != null) { superColumn.addColumn(subColumn.name(), subColumn); break; } } } } return superColumn; }
/** * 读取数据流 * * @param dis * @param header * @param fileTable * @return * @throws Exception */ public static byte[] readFileFromPak(DataInputStream dis, LPKHeader header, LPKTable fileTable) throws Exception { dis.skip(fileTable.getOffSet() - outputOffset(header)); int fileLength = (int) fileTable.getFileSize(); byte[] fileBuff = new byte[fileLength]; int readLength = dis.read(fileBuff, 0, fileLength); if (readLength < fileLength) { return null; } else { makeBuffer(fileBuff, readLength); return fileBuff; } }
/** * Skip exactly <code>n</code> bytes. Throws if less bytes are skipped. * * @param n bytes to skip * @throws java.io.IOException if an I/O error occurs, or less that <code>n</code> bytes were * skipped. */ private void skip(long n) throws IOException { long skiplen = n; while (skiplen > 0) { long skipped = in.skip(skiplen); if (skipped <= 0) { break; } skiplen -= skipped; } if (skiplen != 0) { String msg = "Unable to skip remaining bytes."; throw new IOException(msg); } }
private static int convertNBytesToInt(byte[] buffer, int offset, int nBytes) throws IOException { int value = 0; int shift = 0; ByteArrayInputStream byte_in = new ByteArrayInputStream(buffer); DataInputStream data_in = new DataInputStream(byte_in); /* skip the offset */ data_in.skip(offset); for (int i = 0; i < nBytes; i++) { value += data_in.readUnsignedByte() << shift; shift += 8; } return value; }
public IColumn deserialize(DataInputStream dis, IFilter filter) throws IOException { if (dis.available() == 0) return null; IColumn superColumn = defreezeSuperColumn(dis); superColumn = filter.filter(superColumn, dis); if (superColumn != null) { if (!superColumn.isMarkedForDelete()) fillSuperColumn(superColumn, dis); return superColumn; } else { /* read the number of columns stored */ dis.readInt(); /* read the size of all columns to skip */ int size = dis.readInt(); dis.skip(size); return null; } }
Object readRGB48(InputStream in) throws IOException { if (fi.compression > FileInfo.COMPRESSION_NONE) return readCompressedRGB48(in); int channels = fi.samplesPerPixel; short[][] stack = new short[channels][nPixels]; DataInputStream dis = new DataInputStream(in); int pixel = 0; int min = 65535, max = 0; if (fi.stripLengths == null) { fi.stripLengths = new int[fi.stripOffsets.length]; fi.stripLengths[0] = width * height * bytesPerPixel; } for (int i = 0; i < fi.stripOffsets.length; i++) { if (i > 0) { long skip = (fi.stripOffsets[i] & 0xffffffffL) - (fi.stripOffsets[i - 1] & 0xffffffffL) - fi.stripLengths[i - 1]; if (skip > 0L) dis.skip(skip); } int len = fi.stripLengths[i]; int bytesToGo = (nPixels - pixel) * channels * 2; if (len > bytesToGo) len = bytesToGo; byte[] buffer = new byte[len]; dis.readFully(buffer); int value; int channel = 0; boolean intel = fi.intelByteOrder; for (int base = 0; base < len; base += 2) { if (intel) value = ((buffer[base + 1] & 0xff) << 8) | (buffer[base] & 0xff); else value = ((buffer[base] & 0xff) << 8) | (buffer[base + 1] & 0xff); if (value < min) min = value; if (value > max) max = value; stack[channel][pixel] = (short) (value); channel++; if (channel == channels) { channel = 0; pixel++; } } showProgress(i + 1, fi.stripOffsets.length); } this.min = min; this.max = max; return stack; }
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { int index = -1; if (data != null) { index = data.getIntExtra("index", -1); } switch (resultCode) { case LoadDisk.ID_RESULT_LOADDISK: loadDisk(LoadDisk.selectedDisk, true); if (!showHint("hint_switch_keyboards", R.string.hint_switch_keyboards, 5)) { showHint("hint_space_to_start", R.string.hint_space_to_start, 10); } break; case LoadDisk.ID_RESULT_SAVE: SavedGameInfo info; if (index == -1) { info = new SavedGameInfo(); } else { info = SavedGameInfo.savedGames.remove(index); } SavedGameInfo.savedGames.add(0, info); info.save(this); break; case LoadDisk.ID_RESULT_RESTORE: info = SavedGameInfo.savedGames.get(index); loadDisk(info.diskInfo, false); byte[] buffer = new byte[65 * 1024]; try { FileInputStream fileIn = openFileInput(info.filename); DataInputStream din = new DataInputStream(fileIn); din.skip(info.offsetToMachineData); int cbMachine = din.readInt(); int cb = fileIn.read(buffer); bbcDeserialize(buffer); din.close(); Toast.makeText(this, "Restored", Toast.LENGTH_SHORT).show(); } catch (IOException ex) { Log.d(TAG, "Error restoring state: " + ex); } SavedGameInfo.current = info; break; } }
public static long convert8BytesToLong(byte[] buffer, int offset) throws IOException { ByteArrayInputStream byte_in = new ByteArrayInputStream(buffer); DataInputStream data_in = new DataInputStream(byte_in); /* skip the offset */ data_in.skip(offset); // long value; value = data_in.readUnsignedByte(); value += (long) data_in.readUnsignedByte() << 8; value += (long) data_in.readUnsignedByte() << 16; value += (long) data_in.readUnsignedByte() << 24; value += (long) data_in.readUnsignedByte() << 32; value += (long) data_in.readUnsignedByte() << 40; value += (long) data_in.readUnsignedByte() << 48; value += (long) data_in.readUnsignedByte() << 56; return value; // return convertNBytesToLong(buffer, offset, 8); }
Object readCompressedRGB48(InputStream in) throws IOException { if (fi.compression == FileInfo.LZW_WITH_DIFFERENCING) throw new IOException("ImageJ cannot open 48-bit LZW compressed TIFFs with predictor"); int channels = 3; short[][] stack = new short[channels][nPixels]; DataInputStream dis = new DataInputStream(in); int pixel = 0; int min = 65535, max = 0; for (int i = 0; i < fi.stripOffsets.length; i++) { if (i > 0) { long skip = (fi.stripOffsets[i] & 0xffffffffL) - (fi.stripOffsets[i - 1] & 0xffffffffL) - fi.stripLengths[i - 1]; if (skip > 0L) dis.skip(skip); } int len = fi.stripLengths[i]; byte[] buffer = new byte[len]; dis.readFully(buffer); buffer = uncompress(buffer); len = buffer.length; if (len % 2 != 0) len--; int value; int channel = 0; boolean intel = fi.intelByteOrder; for (int base = 0; base < len && pixel < nPixels; base += 2) { if (intel) value = ((buffer[base + 1] & 0xff) << 8) | (buffer[base] & 0xff); else value = ((buffer[base] & 0xff) << 8) | (buffer[base + 1] & 0xff); if (value < min) min = value; if (value > max) max = value; stack[channel][pixel] = (short) (value); channel++; if (channel == channels) { channel = 0; pixel++; } } showProgress(i + 1, fi.stripOffsets.length); } this.min = min; this.max = max; return stack; }
/** * Read the class's attributes. Since none of the attributes are required, just read the length of * each attribute and skip that many bytes. * * @param in The stream from which to read. * @exception IOException If an error occurs while reading. */ public void readAttributes(DataInputStream in) throws IOException { int numAttributes = in.readUnsignedShort(); attrs = new Attribute[numAttributes]; for (int i = 0; i < numAttributes; i++) { int nameIndex = in.readUnsignedShort(); int length = in.readInt(); String name = (String) constants[nameIndex].value(); Attribute a = createAttribute(in, name, nameIndex, length); if (a != null) { attrs[i] = a; } else { long n = in.skip(length); if (n != length) { throw new EOFException(); } } } }
/** * Read the file at the path specified at the time of instantiation and return a list of peer * records * * @return a list of peer records or null if the list is stale * @throws IOException if any IO operation on the file fails */ @Override public ArrayList<PeerRecord> getPeerList() throws IOException { DataInputStream data = new DataInputStream(new FileInputStream(PEER_FILE_LOCATION)); try { int peerCount = readPeerCount(data); if (peers != null) return peers; ArrayList<PeerRecord> newPeers = new ArrayList<PeerRecord>(); for (int i = 0; i < peerCount; i++) { int addressType = data.read(); byte addr[]; switch (addressType) { case 4: addr = new byte[4]; break; case 6: addr = new byte[16]; break; default: throw new IOException("Invalid address type " + addressType); } data.read(addr); data.skip(32 - addr.length); int linkScore = data.read(); newPeers.add(new PeerRecord(InetAddress.getByAddress(addr), linkScore)); } // only overwrite the peer field when were done, to avoid race // conditions. peers = newPeers; return newPeers; } finally { data.close(); } }
@Override public void decode(byte[] header, ByteBuffer input) throws IOException { assert header != null && header.length == 1 : "input header is invalid"; boolean valid = (header[0] & 0x80) != 0; this.setResponseCode(ResponseCode.valueOf((byte) (header[0] & 0x7F))); DataInputStream in = new DataInputStream(new ByteBufferInputStream(input)); // read in first segment of fixed format sense data in.readByte(); int key = in.readUnsignedByte() & 0x0F; // TODO: FILEMARK, EOM, and ILI are unsupported byte[] info = new byte[4]; in.read(info); int length = in.readUnsignedByte() - 10; // length of next segment, minus required read-in length = length < 0 ? 0 : length; // read in the next segment of the fixed format sense data byte[] cmdi = new byte[4]; in.read(cmdi); int code = in.readUnsignedByte(); int qualifier = in.readUnsignedByte(); in.readByte(); this.senseKeySpecificBuffer = new byte[3]; in.read(this.senseKeySpecificBuffer); // the rest of the additional sense bytes are ignored // (vendor specific bytes not supported) in.skip(length); KCQ kcq = KCQ.valueOf(key, code, qualifier); // throws IOException on invalid values // Set appropriate fields this.setKcq(kcq); this.setInformation(valid ? info : null); this.setCommandSpecificInformation(cmdi); // sense key specific buffer already set, will be decoded when exception is constructed. }
/** * Loads images from the resource and replace palette chunks. * * @param name the name of the resource containing the image data in the PNG format * @param color the color * @return the created image */ private Image[] getColorizedImages(String name, int skip, int color) { InputStream inputStream = getClass().getResourceAsStream(name); DataInputStream dataStream = new DataInputStream(inputStream); Image[] images = null; try { dataStream.skip(skip); int imagesCount = dataStream.readByte(); images = new Image[imagesCount]; for (int i = 0; i < imagesCount; i++) { int imageLength = dataStream.readShort(); byte[] buffer = new byte[imageLength]; dataStream.read(buffer, 0, imageLength); if (!compareBytes(buffer, 0, PNG_SIGNATURE)) { return null; } int paletteOffset = getChunk(buffer, 8, "PLTE"); if (paletteOffset >= 0) { colorizePalette(buffer, paletteOffset, color); images[i] = Image.createImage(buffer, 0, imageLength); } } } catch (Exception e) { } finally { try { inputStream.close(); } catch (IOException e) { } ; } return images; }
@Override public long skip(long n) throws IOException { return in.skip(n); }
public MidiFileFormat getMidiFileFormat(InputStream inputStream) throws InvalidMidiDataException, IOException { DataInputStream dataInputStream = new DataInputStream(inputStream); int nHeaderMagic = dataInputStream.readInt(); if (nHeaderMagic != MidiConstants.HEADER_MAGIC) { throw new InvalidMidiDataException("not a MIDI file: wrong header magic"); } int nHeaderLength = dataInputStream.readInt(); if (nHeaderLength < 6) { throw new InvalidMidiDataException("corrupt MIDI file: wrong header length"); } int nType = dataInputStream.readShort(); if (nType < 0 || nType > 2) { throw new InvalidMidiDataException("corrupt MIDI file: illegal type"); } if (nType == 2) { throw new InvalidMidiDataException("this implementation doesn't support type 2 MIDI files"); } int nNumTracks = dataInputStream.readShort(); if (nNumTracks <= 0) { throw new InvalidMidiDataException("corrupt MIDI file: number of tracks must be positive"); } if (nType == 0 && nNumTracks != 1) { throw new InvalidMidiDataException( "corrupt MIDI file: type 0 files must contain exactely one track"); } int nDivision = dataInputStream.readUnsignedShort(); float fDivisionType = -1.0F; int nResolution = -1; if ((nDivision & 0x8000) != 0) // frame division { int nFrameType = -((nDivision >>> 8) & 0xFF); switch (nFrameType) { case 24: fDivisionType = Sequence.SMPTE_24; break; case 25: fDivisionType = Sequence.SMPTE_25; break; case 29: fDivisionType = Sequence.SMPTE_30DROP; break; case 30: fDivisionType = Sequence.SMPTE_30; break; default: throw new InvalidMidiDataException("corrupt MIDI file: illegal frame division type"); } nResolution = nDivision & 0xff; } else // BPM division { fDivisionType = Sequence.PPQ; nResolution = nDivision & 0x7fff; } // skip additional bytes in the header dataInputStream.skip(nHeaderLength - 6); MidiFileFormat midiFileFormat = new TMidiFileFormat( nType, fDivisionType, nResolution, MidiFileFormat.UNKNOWN_LENGTH, MidiFileFormat.UNKNOWN_LENGTH, nNumTracks); return midiFileFormat; }
public static Globcover[] makeArray(File f) throws IOException { DataInputStream dataStream = new DataInputStream(new BufferedInputStream(new FileInputStream(f))); // read 8 byte header dataStream.skip(8); while (true) { int len = dataStream.readInt(); char[] nameArr = new char[4]; nameArr[0] = (char) dataStream.readByte(); nameArr[1] = (char) dataStream.readByte(); nameArr[2] = (char) dataStream.readByte(); nameArr[3] = (char) dataStream.readByte(); String name = new String(nameArr); if (name.equals("PLTE")) { Globcover[] pallette = new Globcover[256]; for (int i = 0; i < 256; i++) { int r = dataStream.readByte(); int g = dataStream.readByte(); int b = dataStream.readByte(); if (r < 0) r += 256; if (g < 0) g += 256; if (b < 0) b += 256; if (r == 170 && g == 240 && b == 240) { pallette[i] = Globcover.IrrigatedCrops; } else if (r == 255 && g == 255 && b == 100) { pallette[i] = Globcover.RainfedCrops; } else if (r == 220 && g == 240 && b == 100) { pallette[i] = Globcover.CroplandWithVegetation; } else if (r == 205 && g == 205 && b == 102) { pallette[i] = Globcover.VegetationWithCropland; } else if (r == 0 && g == 100 && b == 0) { pallette[i] = Globcover.BroadleafEvergreen; } else if (r == 0 && g == 160 && b == 0) { pallette[i] = Globcover.ClosedBroadleafDeciduous; } else if (r == 170 && g == 200 && b == 0) { pallette[i] = Globcover.OpenBroadleafDeciduous; } else if (r == 0 && g == 60 && b == 0) { pallette[i] = Globcover.ClosedNeedleleafEvergreen; } else if (r == 40 && g == 100 && b == 0) { pallette[i] = Globcover.OpenNeedleleaf; } else if (r == 120 && g == 130 && b == 0) { pallette[i] = Globcover.MixedBroadNeedleleaf; } else if (r == 140 && g == 160 && b == 0) { pallette[i] = Globcover.ForestShrublandWithGrass; } else if (r == 190 && g == 150 && b == 0) { pallette[i] = Globcover.GrassWithForestShrubland; } else if (r == 150 && g == 100 && b == 0) { pallette[i] = Globcover.Shrubland; } else if (r == 255 && g == 180 && b == 50) { pallette[i] = Globcover.Grassland; } else if (r == 255 && g == 235 && b == 175) { pallette[i] = Globcover.SparseVegetation; } else if (r == 0 && g == 120 && b == 90) { pallette[i] = Globcover.FreshFloodedForest; } else if (r == 0 && g == 150 && b == 120) { pallette[i] = Globcover.SalineFloodedForest; } else if (r == 0 && g == 220 && b == 130) { pallette[i] = Globcover.FloodedGrassland; } else if (r == 195 && g == 20 && b == 0) { pallette[i] = Globcover.Urban; } else if (r == 255 && g == 245 && b == 215) { pallette[i] = Globcover.Bare; } else if (r == 0 && g == 70 && b == 200) { pallette[i] = Globcover.Water; } else if (r == 255 && g == 255 && b == 255) { pallette[i] = Globcover.Snow; } else { pallette[i] = Globcover.NoData; } } dataStream.close(); return pallette; } else { dataStream.skip(len + 4); } } }
@Override public long skip(long n) throws IOException { return dataInput.skip(n); }
/** * <code>loadImage</code> is a manual image loader which is entirely independent of AWT. OUT: * RGB888 or RGBA8888 Image object * * @param in InputStream of an uncompressed 24b RGB or 32b RGBA TGA * @param flip Flip the image vertically * @return <code>Image</code> object that contains the image, either as a RGB888 or RGBA8888 * @throws java.io.IOException */ public static Image load(InputStream in, boolean flip) throws IOException { boolean flipH = false; // open a stream to the file DataInputStream dis = new DataInputStream(new BufferedInputStream(in)); // ---------- Start Reading the TGA header ---------- // // length of the image id (1 byte) int idLength = dis.readUnsignedByte(); // Type of color map (if any) included with the image // 0 - no color map data is included // 1 - a color map is included int colorMapType = dis.readUnsignedByte(); // Type of image being read: int imageType = dis.readUnsignedByte(); // Read Color Map Specification (5 bytes) // Index of first color map entry (if we want to use it, uncomment and remove extra read.) // short cMapStart = flipEndian(dis.readShort()); dis.readShort(); // number of entries in the color map short cMapLength = flipEndian(dis.readShort()); // number of bits per color map entry int cMapDepth = dis.readUnsignedByte(); // Read Image Specification (10 bytes) // horizontal coordinate of lower left corner of image. (if we want to use it, uncomment and // remove extra read.) // int xOffset = flipEndian(dis.readShort()); dis.readShort(); // vertical coordinate of lower left corner of image. (if we want to use it, uncomment and // remove extra read.) // int yOffset = flipEndian(dis.readShort()); dis.readShort(); // width of image - in pixels int width = flipEndian(dis.readShort()); // height of image - in pixels int height = flipEndian(dis.readShort()); // bits per pixel in image. int pixelDepth = dis.readUnsignedByte(); int imageDescriptor = dis.readUnsignedByte(); if ((imageDescriptor & 32) != 0) // bit 5 : if 1, flip top/bottom ordering { flip = !flip; } if ((imageDescriptor & 16) != 0) // bit 4 : if 1, flip left/right ordering { flipH = !flipH; } // ---------- Done Reading the TGA header ---------- // // Skip image ID if (idLength > 0) { dis.skip(idLength); } ColorMapEntry[] cMapEntries = null; if (colorMapType != 0) { // read the color map. int bytesInColorMap = (cMapDepth * cMapLength) >> 3; int bitsPerColor = Math.min(cMapDepth / 3, 8); byte[] cMapData = new byte[bytesInColorMap]; dis.read(cMapData); // Only go to the trouble of constructing the color map // table if this is declared a color mapped image. if (imageType == TYPE_COLORMAPPED || imageType == TYPE_COLORMAPPED_RLE) { cMapEntries = new ColorMapEntry[cMapLength]; int alphaSize = cMapDepth - (3 * bitsPerColor); float scalar = 255f / (FastMath.pow(2, bitsPerColor) - 1); float alphaScalar = 255f / (FastMath.pow(2, alphaSize) - 1); for (int i = 0; i < cMapLength; i++) { ColorMapEntry entry = new ColorMapEntry(); int offset = cMapDepth * i; entry.red = (byte) (int) (getBitsAsByte(cMapData, offset, bitsPerColor) * scalar); entry.green = (byte) (int) (getBitsAsByte(cMapData, offset + bitsPerColor, bitsPerColor) * scalar); entry.blue = (byte) (int) (getBitsAsByte(cMapData, offset + (2 * bitsPerColor), bitsPerColor) * scalar); if (alphaSize <= 0) { entry.alpha = (byte) 255; } else { entry.alpha = (byte) (int) (getBitsAsByte(cMapData, offset + (3 * bitsPerColor), alphaSize) * alphaScalar); } cMapEntries[i] = entry; } } } // Allocate image data array Format format; byte[] rawData = null; int dl; if (pixelDepth == 32) { rawData = new byte[width * height * 4]; dl = 4; } else { rawData = new byte[width * height * 3]; dl = 3; } int rawDataIndex = 0; if (imageType == TYPE_TRUECOLOR) { byte red = 0; byte green = 0; byte blue = 0; byte alpha = 0; // Faster than doing a 16-or-24-or-32 check on each individual pixel, // just make a seperate loop for each. if (pixelDepth == 16) { byte[] data = new byte[2]; float scalar = 255f / 31f; for (int i = 0; i <= (height - 1); i++) { if (!flip) { rawDataIndex = (height - 1 - i) * width * dl; } for (int j = 0; j < width; j++) { data[1] = dis.readByte(); data[0] = dis.readByte(); rawData[rawDataIndex++] = (byte) (int) (getBitsAsByte(data, 1, 5) * scalar); rawData[rawDataIndex++] = (byte) (int) (getBitsAsByte(data, 6, 5) * scalar); rawData[rawDataIndex++] = (byte) (int) (getBitsAsByte(data, 11, 5) * scalar); if (dl == 4) { // create an alpha channel alpha = getBitsAsByte(data, 0, 1); if (alpha == 1) { alpha = (byte) 255; } rawData[rawDataIndex++] = alpha; } } } format = dl == 4 ? Format.RGBA8 : Format.RGB8; } else if (pixelDepth == 24) { for (int y = 0; y < height; y++) { if (!flip) { rawDataIndex = (height - 1 - y) * width * dl; } else { rawDataIndex = y * width * dl; } dis.readFully(rawData, rawDataIndex, width * dl); // for (int x = 0; x < width; x++) { // read scanline // blue = dis.readByte(); // green = dis.readByte(); // red = dis.readByte(); // rawData[rawDataIndex++] = red; // rawData[rawDataIndex++] = green; // rawData[rawDataIndex++] = blue; // } } format = Format.BGR8; } else if (pixelDepth == 32) { for (int i = 0; i <= (height - 1); i++) { if (!flip) { rawDataIndex = (height - 1 - i) * width * dl; } for (int j = 0; j < width; j++) { blue = dis.readByte(); green = dis.readByte(); red = dis.readByte(); alpha = dis.readByte(); rawData[rawDataIndex++] = red; rawData[rawDataIndex++] = green; rawData[rawDataIndex++] = blue; rawData[rawDataIndex++] = alpha; } } format = Format.RGBA8; } else { throw new IOException("Unsupported TGA true color depth: " + pixelDepth); } } else if (imageType == TYPE_TRUECOLOR_RLE) { byte red = 0; byte green = 0; byte blue = 0; byte alpha = 0; // Faster than doing a 16-or-24-or-32 check on each individual pixel, // just make a seperate loop for each. if (pixelDepth == 32) { for (int i = 0; i <= (height - 1); ++i) { if (!flip) { rawDataIndex = (height - 1 - i) * width * dl; } for (int j = 0; j < width; ++j) { // Get the number of pixels the next chunk covers (either packed or unpacked) int count = dis.readByte(); if ((count & 0x80) != 0) { // Its an RLE packed block - use the following 1 pixel for the next <count> pixels count &= 0x07f; j += count; blue = dis.readByte(); green = dis.readByte(); red = dis.readByte(); alpha = dis.readByte(); while (count-- >= 0) { rawData[rawDataIndex++] = red; rawData[rawDataIndex++] = green; rawData[rawDataIndex++] = blue; rawData[rawDataIndex++] = alpha; } } else { // Its not RLE packed, but the next <count> pixels are raw. j += count; while (count-- >= 0) { blue = dis.readByte(); green = dis.readByte(); red = dis.readByte(); alpha = dis.readByte(); rawData[rawDataIndex++] = red; rawData[rawDataIndex++] = green; rawData[rawDataIndex++] = blue; rawData[rawDataIndex++] = alpha; } } } } format = Format.RGBA8; } else if (pixelDepth == 24) { for (int i = 0; i <= (height - 1); i++) { if (!flip) { rawDataIndex = (height - 1 - i) * width * dl; } for (int j = 0; j < width; ++j) { // Get the number of pixels the next chunk covers (either packed or unpacked) int count = dis.readByte(); if ((count & 0x80) != 0) { // Its an RLE packed block - use the following 1 pixel for the next <count> pixels count &= 0x07f; j += count; blue = dis.readByte(); green = dis.readByte(); red = dis.readByte(); while (count-- >= 0) { rawData[rawDataIndex++] = red; rawData[rawDataIndex++] = green; rawData[rawDataIndex++] = blue; } } else { // Its not RLE packed, but the next <count> pixels are raw. j += count; while (count-- >= 0) { blue = dis.readByte(); green = dis.readByte(); red = dis.readByte(); rawData[rawDataIndex++] = red; rawData[rawDataIndex++] = green; rawData[rawDataIndex++] = blue; } } } } format = Format.RGB8; } else if (pixelDepth == 16) { byte[] data = new byte[2]; float scalar = 255f / 31f; for (int i = 0; i <= (height - 1); i++) { if (!flip) { rawDataIndex = (height - 1 - i) * width * dl; } for (int j = 0; j < width; j++) { // Get the number of pixels the next chunk covers (either packed or unpacked) int count = dis.readByte(); if ((count & 0x80) != 0) { // Its an RLE packed block - use the following 1 pixel for the next <count> pixels count &= 0x07f; j += count; data[1] = dis.readByte(); data[0] = dis.readByte(); blue = (byte) (int) (getBitsAsByte(data, 1, 5) * scalar); green = (byte) (int) (getBitsAsByte(data, 6, 5) * scalar); red = (byte) (int) (getBitsAsByte(data, 11, 5) * scalar); while (count-- >= 0) { rawData[rawDataIndex++] = red; rawData[rawDataIndex++] = green; rawData[rawDataIndex++] = blue; } } else { // Its not RLE packed, but the next <count> pixels are raw. j += count; while (count-- >= 0) { data[1] = dis.readByte(); data[0] = dis.readByte(); blue = (byte) (int) (getBitsAsByte(data, 1, 5) * scalar); green = (byte) (int) (getBitsAsByte(data, 6, 5) * scalar); red = (byte) (int) (getBitsAsByte(data, 11, 5) * scalar); rawData[rawDataIndex++] = red; rawData[rawDataIndex++] = green; rawData[rawDataIndex++] = blue; } } } } format = Format.RGB8; } else { throw new IOException("Unsupported TGA true color depth: " + pixelDepth); } } else if (imageType == TYPE_COLORMAPPED) { int bytesPerIndex = pixelDepth / 8; if (bytesPerIndex == 1) { for (int i = 0; i <= (height - 1); i++) { if (!flip) { rawDataIndex = (height - 1 - i) * width * dl; } for (int j = 0; j < width; j++) { int index = dis.readUnsignedByte(); if (index >= cMapEntries.length || index < 0) { throw new IOException("TGA: Invalid color map entry referenced: " + index); } ColorMapEntry entry = cMapEntries[index]; rawData[rawDataIndex++] = entry.blue; rawData[rawDataIndex++] = entry.green; rawData[rawDataIndex++] = entry.red; if (dl == 4) { rawData[rawDataIndex++] = entry.alpha; } } } } else if (bytesPerIndex == 2) { for (int i = 0; i <= (height - 1); i++) { if (!flip) { rawDataIndex = (height - 1 - i) * width * dl; } for (int j = 0; j < width; j++) { int index = flipEndian(dis.readShort()); if (index >= cMapEntries.length || index < 0) { throw new IOException("TGA: Invalid color map entry referenced: " + index); } ColorMapEntry entry = cMapEntries[index]; rawData[rawDataIndex++] = entry.blue; rawData[rawDataIndex++] = entry.green; rawData[rawDataIndex++] = entry.red; if (dl == 4) { rawData[rawDataIndex++] = entry.alpha; } } } } else { throw new IOException("TGA: unknown colormap indexing size used: " + bytesPerIndex); } format = dl == 4 ? Format.RGBA8 : Format.RGB8; } else { throw new IOException("Monochrome and RLE colormapped images are not supported"); } in.close(); // Get a pointer to the image memory ByteBuffer scratch = BufferUtils.createByteBuffer(rawData.length); scratch.clear(); scratch.put(rawData); scratch.rewind(); // Create the Image object Image textureImage = new Image(); textureImage.setFormat(format); textureImage.setWidth(width); textureImage.setHeight(height); textureImage.setData(scratch); return textureImage; }
public ByteClass(String name, byte[] classData) { this.name = name; methods = new Vector<String[]>(); properties = new Vector<String[]>(); constructors = new Vector<String[]>(); floatConstants = new Vector<Float>(); longConstants = new Vector<Long>(); methodIndices = new Vector<ReferenceIndex>(); stringIndices = new Vector<ClassConstant<Integer>>(); try { data = classData; stream = new DataInputStream(new ByteArrayInputStream(data)); isValidClass = stream.readInt() == 0xCAFEBABE; if (isValidClass) { minorVersion = stream.readUnsignedShort(); majorVersion = stream.readUnsignedShort(); cpSize = stream.readUnsignedShort(); cpSize--; constants = new ClassConstant<?>[cpSize]; constantTypes = new int[cpSize]; long offset = 10; for (int q = 0; q < cpSize; q++) { byte tag = stream.readByte(); offset++; constantTypes[q] = tag; switch (tag) { case 1: // String int len = stream.readUnsignedShort(); String strVal = ""; for (int i = 0; i < len; i++) strVal += (char) stream.readByte(); constants[q] = new ClassConstant<String>(tag, offset, strVal); offset += 2 + len; break; case 3: // Int constants[q] = new ClassConstant<Integer>(tag, offset, stream.readInt()); offset += 4; break; case 4: // Float float cFloat = stream.readFloat(); constants[q] = new ClassConstant<Float>(tag, offset, cFloat); floatConstants.add(cFloat); offset += 4; break; case 5: // Long long cLong = stream.readLong(); constants[q] = new ClassConstant<Long>(tag, offset, cLong); longConstants.add(cLong); offset += 8; q++; break; case 6: // Double constants[q] = new ClassConstant<Double>(tag, offset, stream.readDouble()); offset += 8; q++; break; case 7: // Class reference constants[q] = new ClassConstant<Integer>(tag, offset, stream.readUnsignedShort()); offset += 2; break; case 8: // String reference ClassConstant<Integer> strRef = new ClassConstant<Integer>(tag, offset, stream.readUnsignedShort()); constants[q] = strRef; stringIndices.add(strRef); offset += 2; break; case 9: // Field reference constants[q] = new ClassConstant<ReferenceIndex>( tag, offset, new ReferenceIndex(stream.readUnsignedShort(), stream.readUnsignedShort())); offset += 4; break; case 10: // Method reference constants[q] = new ClassConstant<ReferenceIndex>( tag, offset, new ReferenceIndex(stream.readUnsignedShort(), stream.readUnsignedShort())); offset += 4; break; case 11: // Interface method reference constants[q] = new ClassConstant<ReferenceIndex>( tag, offset, new ReferenceIndex(stream.readUnsignedShort(), stream.readUnsignedShort())); offset += 4; break; case 12: // Name and type descriptor constants[q] = new ClassConstant<ReferenceIndex>( tag, offset, new ReferenceIndex(stream.readUnsignedShort(), stream.readUnsignedShort())); offset += 4; break; } } // Access Flags accessFlags = stream.readUnsignedShort(); // This class stream.skip(2); // Super class stream.skip(2); // Interfaces int iCount = stream.readUnsignedShort(); stream.skip(iCount * 2); // Fields int fCount = stream.readUnsignedShort(); for (int i = 0; i < fCount; i++) { stream.skip(6); int attributeInfoCount = stream.readUnsignedShort(); for (int q = 0; q < attributeInfoCount; q++) { stream.skip(2); int attributeCount = stream.readInt(); for (int z = 0; z < attributeCount; z++) stream.skip(1); } } // Methods int mCount = stream.readUnsignedShort(); for (int i = 0; i < mCount; i++) { stream.skip(2); methodIndices.add( new ReferenceIndex(stream.readUnsignedShort(), stream.readUnsignedShort())); int attributeInfoCount = stream.readUnsignedShort(); for (int q = 0; q < attributeInfoCount; q++) { stream.skip(2); int attributeCount = stream.readInt(); for (int z = 0; z < attributeCount; z++) stream.skip(1); } } // Attributes stream.close(); } } catch (Exception e) { e.printStackTrace(); System.exit(0); } }
private static void skip(DataInputStream is, long bytes) throws IOException { while (bytes > 0) bytes -= is.skip(bytes); if (bytes != 0) throw new IOException("error in skipping bytes: " + bytes); // $NON-NLS-1$ }
/** * skips samples from the stream. if end of file is reached, it returns the amount that is * actually skipped. * * @param skipAmount amount of samples to skip * @return actual skipped sample count. * @throws IOException if there is a problem while skipping. */ public int skipSamples(int skipAmount) throws IOException { long actualSkipped = dis.skip(skipAmount * format.getBytePerSample()); return (int) actualSkipped / format.getBytePerSample(); }
@Override protected long maybeSkip(long count) throws IOException { return inputStream.skip(count); }