/** Creates a memory-backed encoded image from the stream. The stream is closed. */ protected EncodedImage getByteBufferBackedEncodedImage( InputStream inputStream, int length) throws IOException { CloseableReference<PooledByteBuffer> ref = null; try { if (length <= 0) { ref = CloseableReference.of(mPooledByteBufferFactory.newByteBuffer(inputStream)); } else { ref = CloseableReference.of(mPooledByteBufferFactory.newByteBuffer(inputStream, length)); } return new EncodedImage(ref); } finally { Closeables.closeQuietly(inputStream); CloseableReference.closeSafely(ref); } }
/** * Decodes gif into CloseableImage. * * @param encodedImage input image (encoded bytes plus meta data) * @return a CloseableImage */ public CloseableImage decodeGif( final EncodedImage encodedImage, final int length, final QualityInfo qualityInfo, final ImageDecodeOptions options) { InputStream is = encodedImage.getInputStream(); if (is == null) { return null; } try { if (!options.forceStaticImage && mAnimatedGifDecoder != null) { return mAnimatedGifDecoder.decode(encodedImage, length, qualityInfo, options); } return decodeStaticImage(encodedImage, options); } finally { Closeables.closeQuietly(is); } }
@Override public CloseableImage decode( EncodedImage encodedImage, int length, QualityInfo qualityInfo, ImageDecodeOptions options) { InputStream encodedInputStream = null; try { encodedInputStream = encodedImage.getInputStream(); return new CloseableKeyframesImage( KFImageDeserializer.deserialize(encodedInputStream)); } catch (IOException e) { e.printStackTrace(); return null; } finally { Closeables.closeQuietly(encodedInputStream); } }
private void checkFileInputStream(int size) throws IOException { byte[] bytesToWrite = new byte[size]; for (int i=0; i<size; i++) { bytesToWrite[i] = (byte)i; // It's okay to truncate } File tmpFile = File.createTempFile("streamUtil", "test"); InputStream input = null; OutputStream output = null; try { output = new FileOutputStream(tmpFile); output.write(bytesToWrite); output.close(); input = new FileInputStream(tmpFile); byte[] bytesRead = StreamUtil.getBytesFromStream(input); assertTrue(Arrays.equals(bytesToWrite, bytesRead)); } finally { Closeables.close(input, true); Closeables.close(output, false); assertTrue(tmpFile.delete()); } }
@Override public void release(Closeable value) { try { Closeables.close(value, true); } catch (IOException ioe) { // This will not happen, Closeable.close swallows and logs IOExceptions } }
@Override public void release(Thing value) { try { Closeables.close(value, true); } catch (IOException ioe) { // this should not happen Assert.fail(); } }
/** * Verify that using a ByteArrayInputStream does not allocate a new byte array. */ @Test public void testByteArrayInputStream() throws Exception { byte[] bytes = new byte[8]; InputStream input = new ByteArrayInputStream(bytes); try { byte[] bytesRead = StreamUtil.getBytesFromStream(input); assertTrue(Arrays.equals(bytes, bytesRead)); } finally { Closeables.close(input, true); } }
/** * Verify that using an offset with ByteArrayInputStream still produces correct output. */ @Test public void testByteArrayInputStreamWithOffset() throws Exception { byte[] bytes = new byte[] {0, 1, 2, 3, 4}; InputStream input = new ByteArrayInputStream(bytes, 1, 4); try { byte[] bytesRead = StreamUtil.getBytesFromStream(input); byte[] expectedBytes = new byte[] {1, 2, 3, 4}; assertTrue(Arrays.equals(expectedBytes, bytesRead)); } finally { Closeables.close(input, true); } }
/** * If this is the first time calling this method, the buffer will be checked to make sure it * starts with SOI marker (0xffd8). If the image has been identified as a non-JPEG, data will be * ignored and false will be returned immediately on all subsequent calls. * * This object maintains state of the position of the last read byte. On repeated calls to this * method, it will continue from where it left off. * * @param encodedImage Next set of bytes received by the caller * @return true if a new full scan has been found */ public boolean parseMoreData(final EncodedImage encodedImage) { if (mParserState == NOT_A_JPEG) { return false; } final int dataBufferSize = encodedImage.getSize(); // Is there any new data to parse? // mBytesParsed might be greater than size of dataBuffer - that happens when // we skip more data than is available to read inside doParseMoreData method if (dataBufferSize <= mBytesParsed) { return false; } final InputStream bufferedDataStream = new PooledByteArrayBufferedInputStream( encodedImage.getInputStream(), mByteArrayPool.get(BUFFER_SIZE), mByteArrayPool); try { StreamUtil.skip(bufferedDataStream, mBytesParsed); return doParseMoreData(bufferedDataStream); } catch (IOException ioe) { // Does not happen - streams returned by PooledByteBuffers do not throw IOExceptions Throwables.propagate(ioe); return false; } finally { Closeables.closeQuietly(bufferedDataStream); } }
/** * Reads image header from a file indicated by provided filename and determines * its format. This method does not throw IOException if one occurs. In this case, * {@link ImageFormat#UNKNOWN} will be returned. * @param filename * @return ImageFormat for image stored in filename */ public static ImageFormat getImageFormat(String filename) { FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(filename); return getImageFormat(fileInputStream); } catch (IOException ioe) { return ImageFormat.UNKNOWN; } finally { Closeables.closeQuietly(fileInputStream); } }
@Override public BitmapRegionDecoder intercept(Chain chain) throws IOException { final Uri uri = chain.uri(); BitmapRegionDecoder decoder = chain.chain(uri); if (decoder != null){ return decoder; } if (UriUtil.isNetworkUri(uri)){ ImagePipeline imagePipeline = ImagePipelineFactory.getInstance().getImagePipeline(); ImageRequest request = ImageRequest.fromUri(uri); DataSource<CloseableReference<PooledByteBuffer>> dataSource = imagePipeline.fetchEncodedImage(request,null); try { CloseableReference<PooledByteBuffer> ref = DataSources.waitForFinalResult(dataSource); if (ref == null){ return null; } PooledByteBuffer result = ref.get(); if (BuildConfig.DEBUG) { Log.d("FrescoInterceptor", "从我这加载"); } try { InputStream inputStream = new PooledByteBufferInputStream(result); Closeables.closeQuietly(inputStream); return BitmapRegionDecoder.newInstance(inputStream,false); } catch (IOException e) { ImageRequest imageRequest=ImageRequest.fromUri(uri); CacheKey cacheKey= DefaultCacheKeyFactory.getInstance().getEncodedCacheKey(imageRequest,null); BinaryResource resource = ImagePipelineFactory.getInstance().getMainFileCache().getResource(cacheKey); File file=((FileBinaryResource)resource).getFile(); if (BuildConfig.DEBUG) { Log.d("FrescoInterceptor", file.getName()); } return Interceptors.fixJPEGDecoder(file,e); } } catch (Throwable throwable) { if (BuildConfig.DEBUG) { Log.d("FrescoInterceptor", "intercept: 加载失败了"); } throwable.printStackTrace(); return null; } } return null; }
private void doTransform(EncodedImage encodedImage, @Status int status) { mProducerContext.getListener().onProducerStart(mProducerContext.getId(), PRODUCER_NAME); ImageRequest imageRequest = mProducerContext.getImageRequest(); PooledByteBufferOutputStream outputStream = mPooledByteBufferFactory.newOutputStream(); Map<String, String> extraMap = null; EncodedImage ret = null; InputStream is = null; try { final int softwareNumerator = getSoftwareNumerator( imageRequest, encodedImage, mResizingEnabled); final int downsampleRatio = DownsampleUtil.determineSampleSize(imageRequest, encodedImage); final int downsampleNumerator = calculateDownsampleNumerator(downsampleRatio); final int numerator; if (mUseDownsamplingRatio) { numerator = downsampleNumerator; } else { numerator = softwareNumerator; } is = encodedImage.getInputStream(); if (INVERTED_EXIF_ORIENTATIONS.contains(encodedImage.getExifOrientation())) { // Use exif orientation to rotate since we can't use the rotation angle for // inverted exif orientations final int exifOrientation = getForceRotatedInvertedExifOrientation( imageRequest.getRotationOptions(), encodedImage); extraMap = getExtraMap( encodedImage, imageRequest, numerator, downsampleNumerator, softwareNumerator, 0); JpegTranscoder.transcodeJpegWithExifOrientation( is, outputStream, exifOrientation, numerator, DEFAULT_JPEG_QUALITY); } else { // Use actual rotation angle in degrees to rotate final int rotationAngle = getRotationAngle(imageRequest.getRotationOptions(), encodedImage); extraMap = getExtraMap( encodedImage, imageRequest, numerator, downsampleNumerator, softwareNumerator, rotationAngle); JpegTranscoder.transcodeJpeg( is, outputStream, rotationAngle, numerator, DEFAULT_JPEG_QUALITY); } CloseableReference<PooledByteBuffer> ref = CloseableReference.of(outputStream.toByteBuffer()); try { ret = new EncodedImage(ref); ret.setImageFormat(DefaultImageFormats.JPEG); try { ret.parseMetaData(); mProducerContext.getListener(). onProducerFinishWithSuccess(mProducerContext.getId(), PRODUCER_NAME, extraMap); if (downsampleRatio != DownsampleUtil.DEFAULT_SAMPLE_SIZE) { status |= Consumer.IS_RESIZING_DONE; } getConsumer().onNewResult(ret, status); } finally { EncodedImage.closeSafely(ret); } } finally { CloseableReference.closeSafely(ref); } } catch (Exception e) { mProducerContext.getListener(). onProducerFinishWithFailure(mProducerContext.getId(), PRODUCER_NAME, e, extraMap); if (isLast(status)) { getConsumer().onFailure(e); } return; } finally { Closeables.closeQuietly(is); outputStream.close(); } }