com.facebook.common.internal.ByteStreams Java Examples

The following examples show how to use com.facebook.common.internal.ByteStreams. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DalvikBitmapFactory.java    From FanXin-based-HuanXin with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a bitmap from encoded bytes.
 *
 * @param pooledByteBufferRef the reference to the encoded bytes
 * @return the bitmap
 * @throws TooManyBitmapsException if the pool is full
 * @throws java.lang.OutOfMemoryError if the Bitmap cannot be allocated
 */
synchronized CloseableReference<Bitmap> decodeFromPooledByteBuffer(
    final CloseableReference<PooledByteBuffer> pooledByteBufferRef) {
  final PooledByteBuffer pooledByteBuffer = pooledByteBufferRef.get();
  final int length = pooledByteBuffer.size();

  final byte[] encodedBytesArray = mSingleByteArrayPool.get(length);
  try {
    ByteStreams.readFully(pooledByteBuffer.getStream(), encodedBytesArray, 0, length);
    return doDecodeBitmap(encodedBytesArray, length);
  } catch (IOException ioe) {
    // does not happen, inputStream returned from pooledByteBuffer.getStream does not throw
    // IOExceptions
    throw Throwables.propagate(ioe);
  } finally {
    mSingleByteArrayPool.release(encodedBytesArray);
  }
}
 
Example #2
Source File: DalvikBitmapFactory.java    From FanXin-based-HuanXin with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a bitmap from encoded JPEG bytes. Supports a partial JPEG image.
 *
 * @param pooledByteBufferRef the reference to the encoded bytes
 * @param length the number of encoded bytes in the buffer
 * @return the bitmap
 * @throws TooManyBitmapsException if the pool is full
 * @throws java.lang.OutOfMemoryError if the Bitmap cannot be allocated
 */
synchronized CloseableReference<Bitmap> decodeJPEGFromPooledByteBuffer(
    final CloseableReference<PooledByteBuffer> pooledByteBufferRef,
    int length) {
  final PooledByteBuffer pooledByteBuffer = pooledByteBufferRef.get();
  Preconditions.checkArgument(length <= pooledByteBuffer.size());
  // allocate bigger array in case EOI needs to be added
  final byte[] encodedBytesArray = mSingleByteArrayPool.get(length + 2);
  try {
    ByteStreams.readFully(pooledByteBuffer.getStream(), encodedBytesArray, 0, length);
    if (!endsWithEOI(encodedBytesArray, length)) {
      putEOI(encodedBytesArray, length);
      length += 2;
    }
    return doDecodeBitmap(
        encodedBytesArray,
        length);
  } catch (IOException ioe) {
    // does not happen, streams returned by pooledByteBuffer do not throw IOExceptions
    throw Throwables.propagate(ioe);
  } finally {
    mSingleByteArrayPool.release(encodedBytesArray);
  }
}
 
Example #3
Source File: ImageFormatChecker.java    From FanXin-based-HuanXin with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Reads up to MAX_HEADER_LENGTH bytes from is InputStream. If mark is supported by is, it is
 * used to restore content of the stream after appropriate amount of data is read.
 * Read bytes are stored in imageHeaderBytes, which should be capable of storing
 * MAX_HEADER_LENGTH bytes.
 * @param is
 * @param imageHeaderBytes
 * @return number of bytes read from is
 * @throws IOException
 */
private static int readHeaderFromStream(
    final InputStream is,
    final byte[] imageHeaderBytes)
    throws IOException {
  Preconditions.checkNotNull(is);
  Preconditions.checkNotNull(imageHeaderBytes);
  Preconditions.checkArgument(imageHeaderBytes.length >= MAX_HEADER_LENGTH);

  // If mark is supported by the stream, use it to let the owner of the stream re-read the same
  // data. Otherwise, just consume some data.
  if (is.markSupported()) {
    try {
      is.mark(MAX_HEADER_LENGTH);
      return ByteStreams.read(is, imageHeaderBytes, 0, MAX_HEADER_LENGTH);
    } finally {
      is.reset();
    }
  } else {
    return ByteStreams.read(is, imageHeaderBytes, 0, MAX_HEADER_LENGTH);
  }
}
 
Example #4
Source File: StreamUtil.java    From FanXin-based-HuanXin with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Efficiently fetch the bytes from the InputStream, provided that caller can guess
 * exact numbers of bytes that can be read from inputStream. Avoids one extra byte[] allocation
 * that ByteStreams.toByteArray() performs.
 * @param hint - size of inputStream's content in bytes
 */
public static byte[] getBytesFromStream(InputStream inputStream, int hint) throws IOException {
  // Subclass ByteArrayOutputStream to avoid an extra byte[] allocation and copy
  ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(hint) {
    @Override
    public byte[] toByteArray() {
      // Can only use the raw buffer directly if the size is equal to the array we have.
      // Otherwise we have no choice but to copy.
      if (count == buf.length) {
        return buf;
      } else {
        return super.toByteArray();
      }
    }
  };
  ByteStreams.copy(inputStream, byteOutput);
  return byteOutput.toByteArray();
}
 
Example #5
Source File: ProgressiveJpegParserTest.java    From fresco with MIT License 6 votes vote down vote up
@Before
public void setUp() throws IOException {
  MockitoAnnotations.initMocks(this);
  ByteArrayPool byteArrayPool = mock(ByteArrayPool.class);
  when(byteArrayPool.get(anyInt())).thenReturn(new byte[10]);
  mProgressiveJpegParser = new ProgressiveJpegParser(byteArrayPool);

  mJpegBytes =
      ByteStreams.toByteArray(
          ProgressiveJpegParserTest.class.getResourceAsStream("images/image.jpg"));
  mWebpBytes =
      ByteStreams.toByteArray(
          ProgressiveJpegParserTest.class.getResourceAsStream(("images/image.webp")));
  mPartialWebpBytes = new byte[mWebpBytes.length / 2];
  System.arraycopy(mWebpBytes, 0, mPartialWebpBytes, 0, mPartialWebpBytes.length);
}
 
Example #6
Source File: EncodedImageTest.java    From fresco with MIT License 6 votes vote down vote up
private void checkWebpImage(
    final String imagePath,
    final ImageFormat imageFormat,
    final int expectedWidth,
    final int expectedHeight)
    throws IOException {
  PooledByteBuffer buf =
      new TrivialPooledByteBuffer(
          ByteStreams.toByteArray(EncodedImageTest.class.getResourceAsStream(imagePath)));
  EncodedImage encodedImage = new EncodedImage(CloseableReference.of(buf));
  encodedImage.parseMetaData();
  assertSame(imageFormat, encodedImage.getImageFormat());
  assertEquals(expectedWidth, encodedImage.getWidth());
  assertEquals(expectedHeight, encodedImage.getHeight());
  assertEquals(0, encodedImage.getRotationAngle());
}
 
Example #7
Source File: StreamUtil.java    From fresco with MIT License 6 votes vote down vote up
/**
 * Efficiently fetch the bytes from the InputStream, provided that caller can guess exact numbers
 * of bytes that can be read from inputStream. Avoids one extra byte[] allocation that
 * ByteStreams.toByteArray() performs.
 *
 * @param hint - size of inputStream's content in bytes
 */
public static byte[] getBytesFromStream(InputStream inputStream, int hint) throws IOException {
  // Subclass ByteArrayOutputStream to avoid an extra byte[] allocation and copy
  ByteArrayOutputStream byteOutput =
      new ByteArrayOutputStream(hint) {
        @Override
        public byte[] toByteArray() {
          // Can only use the raw buffer directly if the size is equal to the array we have.
          // Otherwise we have no choice but to copy.
          if (count == buf.length) {
            return buf;
          } else {
            return super.toByteArray();
          }
        }
      };
  ByteStreams.copy(inputStream, byteOutput);
  return byteOutput.toByteArray();
}
 
Example #8
Source File: ImageFormatChecker.java    From fresco with MIT License 6 votes vote down vote up
/**
 * Reads up to maxHeaderLength bytes from is InputStream. If mark is supported by is, it is used
 * to restore content of the stream after appropriate amount of data is read. Read bytes are
 * stored in imageHeaderBytes, which should be capable of storing maxHeaderLength bytes.
 *
 * @param maxHeaderLength the maximum header length
 * @param is
 * @param imageHeaderBytes
 * @return number of bytes read from is
 * @throws IOException
 */
private static int readHeaderFromStream(
    int maxHeaderLength, final InputStream is, final byte[] imageHeaderBytes) throws IOException {
  Preconditions.checkNotNull(is);
  Preconditions.checkNotNull(imageHeaderBytes);
  Preconditions.checkArgument(imageHeaderBytes.length >= maxHeaderLength);

  // If mark is supported by the stream, use it to let the owner of the stream re-read the same
  // data. Otherwise, just consume some data.
  if (is.markSupported()) {
    try {
      is.mark(maxHeaderLength);
      return ByteStreams.read(is, imageHeaderBytes, 0, maxHeaderLength);
    } finally {
      is.reset();
    }
  } else {
    return ByteStreams.read(is, imageHeaderBytes, 0, maxHeaderLength);
  }
}
 
Example #9
Source File: ColorImageExample.java    From fresco with MIT License 5 votes vote down vote up
@Override
public CloseableImage decode(
    EncodedImage encodedImage,
    int length,
    QualityInfo qualityInfo,
    ImageDecodeOptions options) {
  try {
    // Read the file as a string
    String text = new String(ByteStreams.toByteArray(encodedImage.getInputStream()));

    // Check if the string matches "<color>#"
    if (!text.startsWith(COLOR_TAG + "#")) {
      return null;
    }

    // Parse the int value between # and <
    int startIndex = COLOR_TAG.length() + 1;
    int endIndex = text.lastIndexOf('<');
    int color = Integer.parseInt(text.substring(startIndex, endIndex), 16);

    // Add the alpha component so that we actually see the color
    color = ColorUtils.setAlphaComponent(color, 255);

    // Return the CloseableImage
    return new CloseableColorImage(color);
  } catch (IOException e) {
    e.printStackTrace();
  }
  // Return nothing if an error occurred
  return null;
}
 
Example #10
Source File: ArtDecoderTest.java    From fresco with MIT License 5 votes vote down vote up
private static byte[] getDecodedBytes() {
  ArgumentCaptor<InputStream> inputStreamArgumentCaptor =
      ArgumentCaptor.forClass(InputStream.class);
  verifyStatic(BitmapFactory.class, times(2));
  BitmapFactory.decodeStream(
      inputStreamArgumentCaptor.capture(), isNull(Rect.class), any(BitmapFactory.Options.class));
  InputStream decodedStream = inputStreamArgumentCaptor.getValue();
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  try {
    ByteStreams.copy(decodedStream, baos);
  } catch (IOException ioe) {
    throw Throwables.propagate(ioe);
  }
  return baos.toByteArray();
}
 
Example #11
Source File: EncodedImageTest.java    From fresco with MIT License 5 votes vote down vote up
@Test
public void testParseMetaData_PNG() throws IOException {
  PooledByteBuffer buf =
      new TrivialPooledByteBuffer(
          ByteStreams.toByteArray(
              EncodedImageTest.class.getResourceAsStream("images/image.png")));
  EncodedImage encodedImage = new EncodedImage(CloseableReference.of(buf));
  encodedImage.parseMetaData();
  assertSame(DefaultImageFormats.PNG, encodedImage.getImageFormat());
  assertEquals(800, encodedImage.getWidth());
  assertEquals(600, encodedImage.getHeight());
  assertEquals(0, encodedImage.getRotationAngle());
  assertEquals(0, encodedImage.getExifOrientation());
}
 
Example #12
Source File: EncodedImageTest.java    From fresco with MIT License 5 votes vote down vote up
@Test
public void testParseMetaData_JPEG() throws IOException {
  PooledByteBuffer buf =
      new TrivialPooledByteBuffer(
          ByteStreams.toByteArray(
              EncodedImageTest.class.getResourceAsStream("images/image.jpg")));
  EncodedImage encodedImage = new EncodedImage(CloseableReference.of(buf));
  encodedImage.parseMetaData();
  assertSame(DefaultImageFormats.JPEG, encodedImage.getImageFormat());
  assertEquals(550, encodedImage.getWidth());
  assertEquals(468, encodedImage.getHeight());
  assertEquals(0, encodedImage.getRotationAngle());
  assertEquals(0, encodedImage.getExifOrientation());
}
 
Example #13
Source File: TailAppendingInputStreamTest.java    From fresco with MIT License 5 votes vote down vote up
@Test
public void testMark() throws IOException {
  assertEquals(128, mTailAppendingInputStream.read(mOutputBuffer, 0, 128));
  mTailAppendingInputStream.mark(BYTES_LENGTH);
  assertEquals(
      BYTES_LENGTH, ByteStreams.read(mTailAppendingInputStream, mOutputBuffer, 0, BYTES_LENGTH));
  mTailAppendingInputStream.reset();
  for (byte b : Arrays.copyOfRange(mOutputBuffer, 0, BYTES_LENGTH)) {
    assertEquals(((int) b) & 0xFF, mTailAppendingInputStream.read());
  }
}
 
Example #14
Source File: TailAppendingInputStreamTest.java    From fresco with MIT License 5 votes vote down vote up
@Test
public void testDoesNotReadTooMuch_multipleBytes() throws Exception {
  byte[] buffer = new byte[OUTPUT_LENGTH + 1];
  assertEquals(
      OUTPUT_LENGTH, ByteStreams.read(mTailAppendingInputStream, buffer, 0, OUTPUT_LENGTH + 1));
  assertEquals(-1, mTailAppendingInputStream.read());
}
 
Example #15
Source File: WebpDecodingTest.java    From fresco with MIT License 5 votes vote down vote up
private MemoryFile getMemoryFile(String path) {
  try {
    byte[] data = ByteStreams.toByteArray(getTestImageInputStream(path));
    MemoryFile memoryFile = new MemoryFile(null, data.length);
    memoryFile.allowPurging(false);
    memoryFile.writeBytes(data, 0, 0, data.length);
    return memoryFile;
  } catch (IOException e) {
    throw Throwables.propagate(e);
  }
}
 
Example #16
Source File: WebpBitmapFactoryTest.java    From fresco with MIT License 5 votes vote down vote up
@Test
public void testByteArrayDecode() throws Throwable {
  byte[] data = ByteStreams.toByteArray(getTestWebpInputStream());
  final Bitmap bitmap = mWebpBitmapFactory.decodeByteArray(data, 0, data.length, null);

  testBitmapDefault(bitmap, 20, 20);
}
 
Example #17
Source File: WebpBitmapFactoryTest.java    From fresco with MIT License 5 votes vote down vote up
private FileDescriptor getImageFileDescriptor(String path) {
  try {
    File file = File.createTempFile("reqsquare", "tmp");
    byte[] data = ByteStreams.toByteArray(getTestImageInputStream(path));
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(data);
    fos.close();
    return new FileInputStream(file).getFD();
  } catch (IOException e) {
    throw Throwables.propagate(e);
  }
}
 
Example #18
Source File: WriterCallbacks.java    From FanXin-based-HuanXin with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a writer callback that copies all the content read from an {@link InputStream} into
 * the target stream.
 *
 * <p>This writer can be used only once.
 * @param is the source
 * @return the writer callback
 */
public static WriterCallback from(final InputStream is) {
 return new WriterCallback() {
   @Override
   public void write(OutputStream os) throws IOException {
     ByteStreams.copy(is, os);
   }
 };
}
 
Example #19
Source File: TailAppendingInputStreamTest.java    From fresco with MIT License 4 votes vote down vote up
@Test
public void testDoesReadMultipleBytes() throws Exception {
  ByteStreams.readFully(mTailAppendingInputStream, mOutputBuffer, 0, OUTPUT_LENGTH);
  assertArrayEquals(mBytes, Arrays.copyOfRange(mOutputBuffer, 0, BYTES_LENGTH));
  assertArrayEquals(mTail, Arrays.copyOfRange(mOutputBuffer, BYTES_LENGTH, OUTPUT_LENGTH));
}
 
Example #20
Source File: DiskStorageCacheTest.java    From fresco with MIT License 4 votes vote down vote up
private byte[] getContents(BinaryResource resource) throws IOException {
  return ByteStreams.toByteArray(resource.openStream());
}
 
Example #21
Source File: WriterCallbacks.java    From fresco with MIT License 3 votes vote down vote up
/**
 * Creates a writer callback that copies all the content read from an {@link InputStream} into the
 * target stream.
 *
 * <p>This writer can be used only once.
 *
 * @param is the source
 * @return the writer callback
 */
public static WriterCallback from(final InputStream is) {
  return new WriterCallback() {
    @Override
    public void write(OutputStream os) throws IOException {
      ByteStreams.copy(is, os);
    }
  };
}