来自url的位图图像压缩

时间:2014-07-17 07:43:49

标签: android facebook compression image-resizing

你好我有facebook图片,我必须压缩并把它放在我的imageview中。我使用下面的代码调整我的图像大小并压缩它,以便我可以在我的imageview中显示它,但它给文件找不到异常错误

1 个答案:

答案 0 :(得分:0)

我找不到任何方法来压缩位于服务器上的文件/图像。 你可以从URL中获取位图,然后你想重新调整大小。

从URL获取位图。

URL url = new URL("http://....");
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());

调整大小,你可以使用下面的代码

public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);

// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}

使用方法: - 放置此代码: -

private void showImage(final String URL) {
    new Thread(new Runnable() {

        @Override
        public void run() {
            URL url = new URL(URL);
            Bitmap bm = BitmapFactory.decodeStream(url.openConnection()
                    .getInputStream());

            int width = bm.getWidth();
            int height = bm.getHeight();
            float scaleWidth = ((float) YOUR_WIDTH) / width;
            float scaleHeight = ((float) YOUR_HEIGHT) / height;
            // CREATE A MATRIX FOR THE MANIPULATION
            Matrix matrix = new Matrix();
            // RESIZE THE BIT MAP
            matrix.postScale(scaleWidth, scaleHeight);

            // "RECREATE" THE NEW BITMAP
        final   Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width,
                    height, matrix, false);

            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    your_imageView.setImageBitmap(resizedBitmap);
                }
            })
        }
    }).start();
}

感谢。