中心裁切图像在合适的大小对ImageView的设置 [英] center Crop Image In proper size to set on ImageView

查看:373
本文介绍了中心裁切图像在合适的大小对ImageView的设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的摄像头API来拍照,我有根据我的图像查看尺寸大小不同,打开相机。我下面我们进去的Andr​​oid SDK /采样/的Adroid - 18日在名为ApiDemo我已经改变未设置相机的setContentView东西示例项目。我已经设定的框架布局相机。起初我的相机preVIEW是笔挺的,所以我得到了相机的最佳previewSize做出的FrameLayout参数宽度和高度wrap-content.Now相机preVIEW较小然后ImageView的(我想要的大小)。如果我做的FrameLayout参数作为比赛母公司大小,然后相机的看法是stretch.How来解决这个问题。

发现这个链接更多的规范。 <一href=\"http://stackoverflow.com/questions/12751016/android-camera-$p$pview-look-strange/12751221#12751221\">Android相机preVIEW看起来很奇怪

更新

我的相机preVIEW大小是好的,现在我使用的布局方法的想法是我有更大的布局,然后我的ImageView,现在相机preVIEW是好看。
现在我所面临的问题是,设置适当尺寸的图像为了这个,我要在中心同样大小的作物和规模就像我ImageView.this图像I由TakePicture方法获取并保存在SD卡。

对于这个,我用这个方法: -

 公共位图scaleCenterCrop(位图​​源,诠释newHeight,诠释newWidth){
    INT sourceWidth = source.getWidth();
    INT sourceHeight = source.getHeight();    //计算比例分别因素,以适应新的高度和宽度。
    //为了覆盖最终图像,最终的缩放将是更大的
    //这两个。
    浮xScale等=(浮点)newWidth / sourceWidth;
    浮动yScale =(浮点)newHeight / sourceHeight;
    浮规模= Math.max(xScale等,yScale);    缩放时//现在得到源位图的大小
    浮scaledWidth =规模* sourceWidth;
    浮scaledHeight =规模* sourceHeight;    //让我们看看左上角的坐标,如果缩放位图
    //应在由参数给新的大小为中心
    左浮动=(newWidth - scaledWidth)/ 2;
    浮顶=(newHeight - scaledHeight)/ 2;        //为源位图新,图像的缩放目标矩形现在会
        //是
        RectF targetRect =新RectF(左+ 50,上,左+ scaledWidth,顶部+ scaledHeight + 50);
// RectF targetRect =新RectF(0,0,newWidth,newHeight / 2);
        //最后,我们创建指定大小的新位图并绘制我们新的,
        //位图缩放到它。
        位图DEST = Bitmap.createBitmap(newWidth,newHeight,source.getConfig());
        帆布帆布=新的Canvas(DEST);
        canvas.drawBitmap(源,空,targetRect,NULL);        返回DEST;
}

但结果图像质量没有good.Height角是从顶部和底部,以及结果图像质量切割未good.Pixels被拉伸

不要告诉我用scaleType = Center_crop我不能在我的情况下使用它,并且不希望显示裁剪框对用户而言,这一切的过程不应该显示在用户界面。

更新

我根据我的ImageView大小用来从中心和规模作物图像吹法

 位图dstBmp = ThumbnailUtils.extractThumbnail(来源newWidth,newHeight);

但我得到的位图是不一样的期待上的FrameLayout显示相机preVIEW。由于相机preVIEW是big.I认为这些code裁剪的大面积推广。
我试图减少宽度,改变高度,但没有得到其中的比例,我想同样的裁剪后的图像。

还有一个想法图片裁剪最后一帧图像上的FrameLayout自动设​​置后,我有。我们可以从框架布局该集合框架。这怎么可能?

下面是这样的问题,<一个href=\"http://stackoverflow.com/questions/19781598/how-to-retrieve-the-visible-part-of-a-surfaceview-in-android\">How检索在Android上SurfaceView 做任何一个有解决方案的可见部分。

我想通过这条线来实现这个 ThumbnailUtils.extractThumbnail(来源newWidth,newHeight); 并通过这条线我得到的src像图中描述的图像<。 / p>

怎么在这行改变正是????


解决方案

@Akanksha请使用以下code,你只需要通过保存图像的路径,而我们的ImageView的HIGHT和宽度。这code工作完美的我。

 
    进口android.graphics.Bitmap;
进口android.graphics.BitmapFactory;公共类ImageHandler {
    / **
     *德code和从文件样本下一个位图所要求的宽度和
     *高度。
     *
     * @参数文件名
     *文件的完整路径去code
     * @参数reqWidth
     *生成位图的宽度要求
     * @参数reqHeight
     *生成位图的高度要求
     返回:从原来的采样打倒同一方面的位图
     *比率和尺寸是等于或大于更大
     *要求宽度和高度
     * /
公共静态位图德codeSampledBitmapFromFile(字符串的文件名,
            INT reqWidth,诠释reqHeight){        //首先去code。与inJustDe codeBounds = true来检查尺寸
        最后BitmapFactory.Options选项=新BitmapFactory.Options();
        options.inJustDe codeBounds = TRUE;
        BitmapFactory.de codeFILE(文件名,期权);        //计算inSampleSize
        options.inSampleSize = calculateInSampleSize(选项,reqWidth,
                reqHeight);        //德code位与inSampleSize集
        options.inJustDe codeBounds = FALSE;
        返回BitmapFactory.de codeFILE(文件名,期权);
    }公共静态INT calculateInSampleSize(BitmapFactory.Options选项,
            INT reqWidth,诠释reqHeight){
        //原始高度和图像宽度
        最终诠释身高= options.outHeight;
        最终诠释宽度= options.outWidth;
        INT inSampleSize = 1;        如果(高度> reqHeight ||宽度> reqWidth){
            如果(宽度>高){
                inSampleSize = Math.round((浮点)高度/(浮点)reqHeight);
            }其他{
                inSampleSize = Math.round((浮点)宽/(浮点)reqWidth);
            }            //这提供了一些附加的逻辑的情况下,图像具有
            //奇怪
            //宽高比。例如,全景可以具有大得多的
            //宽度大于高度。在这种情况下,总像素可能
            //仍
            //最终会被过大而舒适地适合内存,所以我们
            // 应该
            //更积极与样本缩小图像(=大
            // inSampleSize)。            最终浮动totalPixels =宽*高;            //任何超过2倍的像素要求,我们将品尝下来
            // 进一步。
            最终浮动totalReqPixelsCap = reqWidth * reqHeight * 2;            而(totalPixels /(inSampleSize * inSampleSize)> totalReqPixelsCap){
                inSampleSize ++;
            }
        }
        返回inSampleSize;
    }
}

我叫异步任务,这里面的方法,因为它可能会花费太多UImemory和时间
这是我如何调用它。

 
类Asyncing扩展的AsyncTask {        私人诠释reqWidth;
        私人诠释reqHeight;
        私人ImageView的IV;
        私人字符串文件名;
        私人ProgressDialog PD;        公共Asyncing(INT reqWidth,诠释reqHeight,ImageView的IV,
                字符串文件名){
            超();
            this.reqWidth = reqWidth;
            this.reqHeight = reqHeight;
            this.fileName =文件名;
            this.iv = IV;
        }        @覆盖
        保护位图doInBackground(字符串... PARAMS){
            返回ImageHandler.de codeSampledBitmapFromFile(PARAMS [0]
                    reqWidth,reqHeight);        }        @覆盖
        保护无效onPostExecute(位图结果){
            iv.setImageBitmap(结果);
            如果(pd.isShowing()){
                pd.setMessage(的getString(R.string.completed));
                pd.dismiss();
            }            super.onPostExecute(结果);
        }        @覆盖
        保护无效onProgressUpdate(虚空......值){            super.onProgressUpdate(值);
        }        @覆盖
        在preExecute保护无效(){
            PD = ProgressDialog.show(CustomerDetailsActivity.this,,
                    的getString(R.string.processing_signature));
            super.on preExecute();
        }    }

这是你如何需要调用的AsyncTask

 
signedImagePath = data.getExtras()的getString(的ImagePath);            新Asyncing(signature_img.getWidth(),signature_img.getHeight(),
                    。signature_img,spenTest.png),执行(signedImagePath);

以上code是按照我的要求写的,您可以根据您的修改。

I am using camera API to take picture i have to open camera in different sizes according to my Image view size. I am following the sample project which we get inside Android sdk/sample/adroid-18 at the name "ApiDemo" the thing i have changed is not set camera on setcontentview. I have set the camera on Frame Layout. at first my camera preview was starched so i got the camera OptimalPreviewSize and make FrameLayout parameter width and height as wrap-content.Now the camera preview is smaller then ImageView (The size i want). If i make the size of FrameLayout parameter as match-parent then camera View is stretch.How to resolve this issue.

find this link for more specification. Android camera preview look strange

UPDATE

My camera preview size is fine now i use the on Layout method the idea was i have the bigger layout then my ImageView and now camera preview is looking good. Now the Problem I am facing is set the image of proper size for this I have to center crop and scale in same size in like my ImageView.this Image i get by TakePicture method and saved in sdcard.

For this I am using this method:-

    public Bitmap scaleCenterCrop(Bitmap source, int newHeight, int newWidth) {
    int sourceWidth = source.getWidth();
    int sourceHeight = source.getHeight();

    // Compute the scaling factors to fit the new height and width, respectively.
    // To cover the final image, the final scaling will be the bigger 
    // of these two.
    float xScale = (float) newWidth / sourceWidth;
    float yScale = (float) newHeight / sourceHeight;
    float scale = Math.max(xScale, yScale);

    // Now get the size of the source bitmap when scaled
    float scaledWidth = scale * sourceWidth;
    float scaledHeight = scale * sourceHeight;

    // Let's find out the upper left coordinates if the scaled bitmap
    // should be centered in the new size give by the parameters
    float left = (newWidth - scaledWidth) / 2;
    float top = (newHeight - scaledHeight) / 2;

        // The target rectangle for the new, scaled version of the source bitmap will now
        // be
        RectF targetRect = new RectF(left+50, top, left + scaledWidth, top + scaledHeight+50);
//      RectF targetRect = new RectF(0, 0, newWidth, newHeight/2);
        // Finally, we create a new bitmap of the specified size and draw our new,
        // scaled bitmap onto it.
        Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig());
        Canvas canvas = new Canvas(dest);
        canvas.drawBitmap(source, null, targetRect, null);

        return dest;
}

But the result image quality is not good.Height Corners are cutting from top and bottom, and result image quality is not good.Pixels are stretching.

Don't tell me to use scaleType=Center_crop i can't use it in my case,and don't want to show cropping frame to user,this all process should not show on UI.

UPDATE

I used blow method for crop image from center and scale according to my imageView size

Bitmap dstBmp = ThumbnailUtils.extractThumbnail(source, newWidth, newHeight);

But the bitmap i got is not looking same the camera preview shown on FrameLayout. because camera preview is big.I think these code cropped the large area. I tried to reduce the width and change the height but not getting the same cropped image in which ratio i want.

One more idea i have after picture crop a last image frame set automatically on FrameLayout. can we get that set frame from Frame Layout. How is this possible?

Here is question like this How to retrieve the visible part of a SurfaceView in Android do any one have solution.

I want to achieve this by this line ThumbnailUtils.extractThumbnail(source, newWidth, newHeight);and by this line i am getting src like image described in diagram .

What to change in this line exactly ????

解决方案

@Akanksha Please use this below code, you just need to pass the path of the saved image, and the hight and width of our imageview. This code works perfectly for me.


    import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class ImageHandler {
    /**
     * Decode and sample down a bitmap from a file to the requested width and
     * height.
     * 
     * @param filename
     *            The full path of the file to decode
     * @param reqWidth
     *            The requested width of the resulting bitmap
     * @param reqHeight
     *            The requested height of the resulting bitmap
     * @return A bitmap sampled down from the original with the same aspect
     *         ratio and dimensions that are equal to or greater than the
     *         requested width and height
     */


public static Bitmap decodeSampledBitmapFromFile(String filename,
            int reqWidth, int reqHeight) {

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filename, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth,
                reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filename, options);
    }



public static int calculateInSampleSize(BitmapFactory.Options options,
            int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            if (width > height) {
                inSampleSize = Math.round((float) height / (float) reqHeight);
            } else {
                inSampleSize = Math.round((float) width / (float) reqWidth);
            }

            // This offers some additional logic in case the image has a
            // strange
            // aspect ratio. For example, a panorama may have a much larger
            // width than height. In these cases the total pixels might
            // still
            // end up being too large to fit comfortably in memory, so we
            // should
            // be more aggressive with sample down the image (=larger
            // inSampleSize).

            final float totalPixels = width * height;

            // Anything more than 2x the requested pixels we'll sample down
            // further.
            final float totalReqPixelsCap = reqWidth * reqHeight * 2;

            while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
                inSampleSize++;
            }
        }
        return inSampleSize;
    }
}

I call this method inside async task because it may take too much UImemory and time Here is how I call it.


class Asyncing extends AsyncTask {

        private int reqWidth;
        private int reqHeight;
        private ImageView iv;
        private String fileName;
        private ProgressDialog pd;

        public Asyncing(int reqWidth, int reqHeight, ImageView iv,
                String fileName) {
            super();
            this.reqWidth = reqWidth;
            this.reqHeight = reqHeight;
            this.fileName = fileName;
            this.iv = iv;
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            return ImageHandler.decodeSampledBitmapFromFile(params[0],
                    reqWidth, reqHeight);

        }

        @Override
        protected void onPostExecute(Bitmap result) {
            iv.setImageBitmap(result);
            if (pd.isShowing()) {
                pd.setMessage(getString(R.string.completed));
                pd.dismiss();
            }

            super.onPostExecute(result);
        }

        @Override
        protected void onProgressUpdate(Void... values) {

            super.onProgressUpdate(values);
        }

        @Override
        protected void onPreExecute() {
            pd = ProgressDialog.show(CustomerDetailsActivity.this, "",
                    getString(R.string.processing_signature));
            super.onPreExecute();
        }

    }

This is how you need to call the asynctask


signedImagePath = data.getExtras().getString("imagePath");

            new Asyncing(signature_img.getWidth(), signature_img.getHeight(),
                    signature_img, "spenTest.png").execute(signedImagePath);

above code is written according to my requirements,you modify it according to yours.

这篇关于中心裁切图像在合适的大小对ImageView的设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆