android.graphics.BitmapFactory#decodeStream ( )源码实例Demo

下面列出了android.graphics.BitmapFactory#decodeStream ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: kcanotify_h5-master   文件: KcaUtils.java

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;
}
 
源代码2 项目: cloudinary_android   文件: Utils.java

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);
}
 
源代码3 项目: browser   文件: ImageUtil.java

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;
		}

	}
 
源代码4 项目: HaiNaBaiChuan   文件: CropImageActivity.java

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;
}
 
源代码5 项目: PdfBox-Android   文件: JPEGFactory.java

/**
 * 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;
}
 

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();
        }
    }
}
 

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;
    }
}
 

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;
}
 

/**
 * 处理裁剪,获取裁剪后的图片
 */
public static Bitmap dealCrop(Context context) {
    Bitmap bitmap = null;
    try {
        bitmap = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(cropPictureTempUri));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return bitmap;
}
 

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);
}
 

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);
}
 

/**
 * 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;
}
 

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;
}
 
源代码14 项目: WliveTV   文件: BaseImageDecoder.java

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);
}
 
源代码15 项目: Dali   文件: ImageReference.java

/**
 * 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");
}
 
源代码16 项目: Flora   文件: BatchActivity.java

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();
    }
}
 

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);
        }
    }
}
 
源代码18 项目: FixMath   文件: ImageUtil.java

public void loadBackgroundSecond(int id) {
    background1 = BitmapFactory.decodeStream(getResources().openRawResource(id));
    bg1 = new BitmapDrawable(getResources(), background1);
    bgimg1.setImageDrawable(bg1);
}
 
源代码19 项目: BobEngine   文件: GraphicsHelper.java

/**
 * 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();
}
 

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);
        }
    }
}