Java Code Examples for android.graphics.BitmapFactory#decodeStream()

The following examples show how to use android.graphics.BitmapFactory#decodeStream() . 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: JPEGFactory.java    From PdfBox-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new JPEG Image XObject from an input stream containing JPEG data.
 *
 * The input stream data will be preserved and embedded in the PDF file without modification.
 * @param document the document where the image will be created
 * @param stream a stream of JPEG data
 * @return a new Image XObject
 *
 * @throws IOException if the input stream cannot be read
 */
public static PDImageXObject createFromStream(PDDocument document, InputStream stream)
    throws IOException
{
    // copy stream
    ByteArrayInputStream byteStream = new ByteArrayInputStream(IOUtils.toByteArray(stream));

    // read image
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(byteStream, null, options);
    byteStream.reset();

    // create Image XObject from stream
    PDImageXObject pdImage = new PDImageXObject(document, byteStream,
        COSName.DCT_DECODE, options.outWidth, options.outHeight,
        8, //awtImage.getColorModel().getComponentSize(0),
        PDDeviceRGB.INSTANCE //getColorSpaceFromAWT(awtImage)); // TODO: PdfBox-Android
    );

    return pdImage;
}
 
Example 2
Source File: CropImageActivity.java    From HaiNaBaiChuan with Apache License 2.0 6 votes vote down vote up
private int calculateBitmapSampleSize(Uri bitmapUri) throws IOException {
    InputStream is = null;
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    try {
        is = getContentResolver().openInputStream(bitmapUri);
        BitmapFactory.decodeStream(is, null, options); // Just get image size
    } finally {
        CropUtil.closeSilently(is);
    }

    int maxSize = getMaxImageSize();
    int sampleSize = 1;
    while (options.outHeight / sampleSize > maxSize || options.outWidth / sampleSize > maxSize) {
        sampleSize = sampleSize << 1;
    }
    return sampleSize;
}
 
Example 3
Source File: ImageUtil.java    From browser with GNU General Public License v2.0 6 votes vote down vote up
public static Bitmap getBitmap(String src) {

		try {
			URL url = new URL(src);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setDoInput(true);
			connection.connect();
			InputStream input = connection.getInputStream();
			Bitmap myBitmap = BitmapFactory.decodeStream(input);
			return myBitmap;
			
		} catch (IOException e) {
			return null;
		}

	}
 
Example 4
Source File: KcaUtils.java    From kcanotify_h5-master with GNU General Public License v3.0 6 votes vote down vote up
public static boolean checkFairyImageFileFromStorage(Context context, String name) {
    ContextWrapper cw = new ContextWrapper(context);
    File directory = cw.getDir("fairy", Context.MODE_PRIVATE);
    File myImageFile = new File(directory, KcaUtils.format("%s", name));
    Bitmap bitmap = null;
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    try {
        InputStream is = new FileInputStream(myImageFile);
        bitmap = BitmapFactory.decodeStream(is, null, options);
        is.close();
    } catch (IOException e) {
        // Log.e("KCA", getStringFromException(e));
        return false;
    }
    if (bitmap == null) {
        return false;
    }
    return true;
}
 
Example 5
Source File: Utils.java    From cloudinary_android with MIT License 6 votes vote down vote up
public static Bitmap decodeBitmapStream(Context context, Uri uri, int reqWidth, int reqHeight) throws IOException {
    InputStream is = context.getContentResolver().openInputStream(uri);

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(is, null, options);
    is.close();
    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    is = context.getContentResolver().openInputStream(uri);
    Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);
    is.close();
    return bitmap == null ? null : getCroppedBitmap(bitmap);
}
 
Example 6
Source File: ImageResizer.java    From react-native-pixel-color with MIT License 5 votes vote down vote up
/**
 * Load a bitmap either from a real file or using the {@link ContentResolver} of the current
 * {@link Context} (to read gallery images for example).
 */
private static Bitmap loadBitmap(Context context, String imagePath, BitmapFactory.Options options) throws IOException {
    Bitmap sourceImage = null;
    if (!imagePath.startsWith("content://") && !imagePath.startsWith("file://")) {
        sourceImage = BitmapFactory.decodeFile(imagePath, options);
    } else {
        ContentResolver cr = context.getContentResolver();
        InputStream input = cr.openInputStream(Uri.parse(imagePath));
        if (input != null) {
            sourceImage = BitmapFactory.decodeStream(input, null, options);
            input.close();
        }
    }
    return sourceImage;
}
 
Example 7
Source File: ImageDownloader.java    From platform-friends-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static void readFromCache(RequestKey key, Context context, boolean allowCachedRedirects) {
    InputStream cachedStream = null;
    boolean isCachedRedirect = false;
    if (allowCachedRedirects) {
        URI redirectUri = UrlRedirectCache.getRedirectedUri(context, key.uri);
        if (redirectUri != null) {
            cachedStream = ImageResponseCache.getCachedImageStream(redirectUri, context);
            isCachedRedirect = cachedStream != null;
        }
    }

    if (!isCachedRedirect) {
        cachedStream = ImageResponseCache.getCachedImageStream(key.uri, context);
    }

    if (cachedStream != null) {
        // We were able to find a cached image.
        Bitmap bitmap = BitmapFactory.decodeStream(cachedStream);
        Utility.closeQuietly(cachedStream);
        issueResponse(key, null, bitmap, isCachedRedirect);
    } else {
        // Once the old downloader context is removed, we are thread-safe since this is the
        // only reference to it
        DownloaderContext downloaderContext = removePendingRequest(key);
        if (downloaderContext != null && !downloaderContext.isCancelled) {
            enqueueDownload(downloaderContext.request, key);
        }
    }
}
 
Example 8
Source File: BatchActivity.java    From Flora with MIT License 5 votes vote down vote up
private void testBitmap() {
    try {
        Bitmap[] bitmaps = new Bitmap[4];
        long[] sizes = new long[4];
        for (int index = 0; index < 4; index++) {
            int n = index + 1;
            final InputStream is = getResources().getAssets().open("test" + n + ".jpg");
            long fileSize = is.available();
            Bitmap originBitmap = BitmapFactory.decodeStream(is);

            bitmaps[index] = originBitmap;
            sizes[index] = fileSize;

            is.close();
        }

        setupSourceInfo(bitmaps, sizes);

        Flora.with().load(bitmaps).compress(new Callback<List<String>>() {
            @Override
            public void callback(List<String> strings) {
                setupResultInfo(strings);
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 9
Source File: ImageReference.java    From Dali with Apache License 2.0 5 votes vote down vote up
/**
 * This will synchronously load the bitmap (if needed) maybe don't
 * call this in the main thread. Loading of large bitmaps can take up
 * 500 ms+ on faster devices.
 *
 * @param resources {@link android.content.Context#getResources()}
 * @return the loaded bitmap. If custom options are provided these will be used here
 */
public Bitmap synchronouslyLoadBitmap(Resources resources) {
    if (bitmap != null) {
        if (decoderOptions != null && decoderOptions.inSampleSize > 1) {
            return Bitmap.createScaledBitmap(bitmap, bitmap.getWidth() / decoderOptions.inSampleSize, bitmap.getHeight() / decoderOptions.inSampleSize, false);
        } else {
            return bitmap;
        }
    } else if (resId != null) {
        return BitmapFactory.decodeResource(resources, resId, decoderOptions);
    } else if (fileToBitmap != null) {
        return BitmapFactory.decodeFile(fileToBitmap.getAbsolutePath(), decoderOptions);
    } else if (inputStream != null) {
        return BitmapFactory.decodeStream(inputStream, null, decoderOptions);
    } else if (view != null) {
        int downSample = 1;
        Bitmap.Config config = Bitmap.Config.ARGB_8888;
        if (decoderOptions != null) {
            if (decoderOptions.inSampleSize > 1) {
                downSample = decoderOptions.inSampleSize;
            }
            if (decoderOptions.inPreferredConfig != null) {
                config = decoderOptions.inPreferredConfig;
            }
        }
        return BuilderUtil.drawViewToBitmap(bitmap, view, downSample, config);
    }
    throw new IllegalStateException("No image resource was set");
}
 
Example 10
Source File: BaseImageDecoder.java    From WliveTV with Apache License 2.0 5 votes vote down vote up
protected ImageFileInfo defineImageSizeAndRotation(InputStream imageStream, ImageDecodingInfo decodingInfo)
		throws IOException {
	Options options = new Options();
	options.inJustDecodeBounds = true;
	BitmapFactory.decodeStream(imageStream, null, options);

	ExifInfo exif;
	String imageUri = decodingInfo.getImageUri();
	if (decodingInfo.shouldConsiderExifParams() && canDefineExifParams(imageUri, options.outMimeType)) {
		exif = defineExifOrientation(imageUri);
	} else {
		exif = new ExifInfo();
	}
	return new ImageFileInfo(new ImageSize(options.outWidth, options.outHeight, exif.rotation), exif);
}
 
Example 11
Source File: LoadImageUtil.java    From natrium-android-wallet with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public Bitmap loadImageBitmap(Context context, String imageName) {
    Bitmap bitmap = null;
    FileInputStream fiStream;
    try {
        fiStream = context.openFileInput(imageName);
        bitmap = BitmapFactory.decodeStream(fiStream);
        fiStream.close();
    } catch (Exception e) {
        Timber.e("Failed to load image from disk: %s", imageName);
        e.printStackTrace();
    }
    return bitmap;
}
 
Example 12
Source File: BitmapHelper.java    From react-native-streaming-audio-player with MIT License 5 votes vote down vote up
public static Bitmap scaleBitmap(int scaleFactor, InputStream is) {
    // Get the dimensions of the bitmap
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();

    // Decode the image file into a Bitmap sized to fill the View
    bmOptions.inJustDecodeBounds = false;
    bmOptions.inSampleSize = scaleFactor;

    return BitmapFactory.decodeStream(is, null, bmOptions);
}
 
Example 13
Source File: BitmapHelper.java    From react-native-audio-streaming-player with MIT License 5 votes vote down vote up
public static Bitmap scaleBitmap(int scaleFactor, InputStream is) {
    // Get the dimensions of the bitmap
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();

    // Decode the image file into a Bitmap sized to fill the View
    bmOptions.inJustDecodeBounds = false;
    bmOptions.inSampleSize = scaleFactor;

    return BitmapFactory.decodeStream(is, null, bmOptions);
}
 
Example 14
Source File: PictureSelectUtils.java    From PictureSelector with Apache License 2.0 5 votes vote down vote up
/**
 * 处理裁剪,获取裁剪后的图片
 */
public static Bitmap dealCrop(Context context) {
    Bitmap bitmap = null;
    try {
        bitmap = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(cropPictureTempUri));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return bitmap;
}
 
Example 15
Source File: EndlessTaggingActivity.java    From Android-SDK with MIT License 5 votes vote down vote up
protected Bitmap doInBackground( String... urls )
{
  String urlDisplay = urls[ 0 ];
  Bitmap bitmap = null;
  try
  {
    InputStream inputStream = new java.net.URL( urlDisplay ).openStream();
    bitmap = BitmapFactory.decodeStream( inputStream );
  }
  catch( Exception e )
  {
    e.printStackTrace();
  }
  return bitmap;
}
 
Example 16
Source File: ReactNativeUtil.java    From react-native-azurenotificationhub with MIT License 5 votes vote down vote up
public static Bitmap fetchImage(String urlString) {
    try {
        HttpURLConnection connection = UrlWrapper.openConnection(urlString);
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        return BitmapFactory.decodeStream(input);
    } catch (Exception e) {
        Log.e(TAG, ERROR_FETCH_IMAGE, e);
        return null;
    }
}
 
Example 17
Source File: ImageViewer.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
public void setImage(final String uri) throws IOException {
    InputStream is = null;
    try {
        URLConnection conn = new URL(uri).openConnection();
        conn.setRequestProperty(DConnectMessage.HEADER_GOTAPI_ORIGIN, mOrigin);
        is = conn.getInputStream();
        Bitmap bitmap = BitmapFactory.decodeStream(is);
        mTexture = BitmapUtils.resize(bitmap, 2048, 1024);
    } finally {
        if (is != null) {
            is.close();
        }
    }
}
 
Example 18
Source File: KCWebImageDownloader.java    From kerkee_android with GNU General Public License v3.0 4 votes vote down vote up
private void writeBitmapToFile(String targetPath, InputStream inputStream) throws IOException
{
    File file = new File(targetPath);
    synchronized (object)
    {
        if (!file.getParentFile().exists())
        {
            file.getParentFile().mkdirs();
        }
    }
    String name = file.getName().toLowerCase();
    Bitmap.CompressFormat format;
    if (name.contains("jpg") || name.contains("jpeg"))
    {
        format = Bitmap.CompressFormat.JPEG;
    }
    else if (name.contains("png"))
    {
        format = Bitmap.CompressFormat.PNG;
    }
    else if (name.contains("webp"))
    {
        if (Build.VERSION.SDK_INT >= 14) format = Bitmap.CompressFormat.WEBP;
        else format = Bitmap.CompressFormat.JPEG;
    }
    else
    {
        format = Bitmap.CompressFormat.JPEG;
    }
    //write to file
    try
    {
        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        OutputStream fileOut = new BufferedOutputStream(fileOutputStream);
        bitmap.compress(format, 100, fileOut);
        bitmap.recycle();
        fileOut.flush();
        fileOut.close();
        fileOutputStream.close();
    }
    catch (Exception e)
    {
        if (KCLog.DEBUG)
        {
            KCLog.e(e);
        }
    }
    catch (OutOfMemoryError error)
    {
        if (KCLog.DEBUG)
        {
            KCLog.e(error);
        }
    }
}
 
Example 19
Source File: ImageUtil.java    From FixMath with Apache License 2.0 4 votes vote down vote up
public void loadBackgroundSecond(int id) {
    background1 = BitmapFactory.decodeStream(getResources().openRawResource(id));
    bg1 = new BitmapDrawable(getResources(), background1);
    bgimg1.setImageDrawable(bg1);
}
 
Example 20
Source File: GraphicsHelper.java    From BobEngine with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Load a particular graphic.
 * 
 * @param gl The OpenGL object to handle gl functions
 * @param g The index of the graphic in graphics[] to load
 * @param sampleSize The sample size to load the graphic.
 */
private void loadGraphic(GL11 gl, int g, int sampleSize) {
	Bitmap bmp;
	BitmapFactory.Options op = new BitmapFactory.Options();
	op.inSampleSize = sampleSize;

	InputStream is = context.getResources().openRawResource(graphics[g].drawable);

	try {
		bmp = BitmapFactory.decodeStream(is, null, op);
	} finally {
		try {
			is.close();
		} catch (IOException e) {
			Log.e("BobEngine", "Failed to load graphic.");
			e.printStackTrace();
		}
	}

	// Generate an ID for the graphic
	final int[] texID = new int[1];
	gl.glGenTextures(1, texID, 0);
	graphics[g].id = texID[0];

	// Tell openGL which texture we are working with
	gl.glBindTexture(GL11.GL_TEXTURE_2D, graphics[g].id);

	// Create mipmaps and set texture parameters.
	gl.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, graphics[g].minFilter);                 // Filtering for downscaling
	gl.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, graphics[g].magFilter);                 // Upscale filtering
	if (graphics[g].useMipMaps) gl.glTexParameterx(GL11.GL_TEXTURE_2D, GL11.GL_GENERATE_MIPMAP, GL11.GL_TRUE); // Use mipmapping

	// Texture wrapping
	if (graphics[g].repeating) {
		gl.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT);
		gl.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT);
	} else {
		gl.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_CLAMP_TO_EDGE);
		gl.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_CLAMP_TO_EDGE);
	}

	// This assigns bmp to the texture we are working with (g)
	GLUtils.texImage2D(GL11.GL_TEXTURE_2D, 0, bmp, 0);

	// Set the face rotation
	gl.glFrontFace(GL11.GL_CCW);

	bmp.recycle();

	graphics[g].loaded();

	gl.glFinish();
}