1. /*
  2. * @(#)SubImageInputStream.java 1.12 03/01/23
  3. *
  4. * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package com.sun.imageio.plugins.common;
  8. import java.io.IOException;
  9. import javax.imageio.stream.ImageInputStreamImpl;
  10. import javax.imageio.stream.ImageInputStream;
  11. /**
  12. * @version 0.5
  13. */
  14. public class SubImageInputStream extends ImageInputStreamImpl {
  15. ImageInputStream stream;
  16. long startingPos;
  17. int startingLength;
  18. int length;
  19. public SubImageInputStream(ImageInputStream stream, int length)
  20. throws IOException {
  21. this.stream = stream;
  22. this.startingPos = stream.getStreamPosition();
  23. this.startingLength = this.length = length;
  24. }
  25. public int read() throws IOException {
  26. if (length == 0) { // Local EOF
  27. return -1;
  28. } else {
  29. --length;
  30. return stream.read();
  31. }
  32. }
  33. public int read(byte[] b, int off, int len) throws IOException {
  34. if (length == 0) { // Local EOF
  35. return -1;
  36. }
  37. len = Math.min(len, length);
  38. int bytes = stream.read(b, off, len);
  39. length -= bytes;
  40. return bytes;
  41. }
  42. public long length() {
  43. return startingLength;
  44. }
  45. public void seek(long pos) throws IOException {
  46. stream.seek(pos - startingPos);
  47. streamPos = pos;
  48. }
  49. }