保存在 ImageView 中时,从自定义相机拍摄的图像会被拉伸

2024-05-04

我正在使用此代码在 Imageview 中保存图片,但在 imageview 中保存时图像被拉伸。相机预览是完美的,单击右侧图像,但是当我在 imageview 中设置该图像时,图像被拉伸。

    public void onPicTaken(byte[] data) {

    if (data != null) {
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        int screenHeight = getResources().getDisplayMetrics().heightPixels;
        Bitmap bm = BitmapFactory.decodeByteArray(data, 0, (data != null) ? data.length : 0);

        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            // Notice that width and height are reversed
            Bitmap scaled = Bitmap.createScaledBitmap(bm, screenHeight, screenWidth, true);
            int w = scaled.getWidth();
            int h = scaled.getHeight();
            // Setting post rotate to 90
            Matrix mtx = new Matrix();
            mtx.postRotate(90);
            // Rotating Bitmap
            bm = Bitmap.createBitmap(scaled, 0, 0, w, h, mtx, true);
        }else{// LANDSCAPE MODE
            //No need to reverse width and height
            Bitmap scaled = Bitmap.createScaledBitmap(bm, screenWidth,screenHeight , true);
            bm=scaled;
        }
        ivCaptureImagePreview.setImageBitmap(bm);
        ivCaptureImagePreview.setVisibility(View.VISIBLE);
    }

}

使用以下类创建缩放位图

public class ScalingUtilities 
{
     /**
     * Utility function for decoding an image resource. The decoded bitmap will
     * be optimized for further scaling to the requested destination dimensions
     * and scaling logic.
     *
     * @param res The resources object containing the image data
     * @param resId The resource id of the image data
     * @param dstWidth Width of destination area
     * @param dstHeight Height of destination area
     * @param scalingLogic Logic to use to avoid image stretching
     * @return Decoded bitmap
     */
    public static Bitmap decodeResource(Resources res, int resId, int dstWidth, int dstHeight,
            ScalingLogic scalingLogic) {
        Options options = new Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);
        options.inJustDecodeBounds = false;
        options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, dstWidth,
                dstHeight, scalingLogic);
        Bitmap unscaledBitmap = BitmapFactory.decodeResource(res, resId, options);

        return unscaledBitmap;
    }

    /**
     * Utility function for creating a scaled version of an existing bitmap
     *
     * @param unscaledBitmap Bitmap to scale
     * @param dstWidth Wanted width of destination bitmap
     * @param dstHeight Wanted height of destination bitmap
     * @param scalingLogic Logic to use to avoid image stretching
     * @return New scaled bitmap object
     */
    public static Bitmap createScaledBitmap(Bitmap unscaledBitmap, int dstWidth, int dstHeight,
            ScalingLogic scalingLogic) {
        Rect srcRect = calculateSrcRect(unscaledBitmap.getWidth(), unscaledBitmap.getHeight(),
                dstWidth, dstHeight, scalingLogic);
        Rect dstRect = calculateDstRect(unscaledBitmap.getWidth(), unscaledBitmap.getHeight(),
                dstWidth, dstHeight, scalingLogic);
        Bitmap scaledBitmap = Bitmap.createBitmap(dstRect.width(), dstRect.height(),
                Config.ARGB_8888);
        Canvas canvas = new Canvas(scaledBitmap);
        canvas.drawBitmap(unscaledBitmap, srcRect, dstRect, new Paint(Paint.FILTER_BITMAP_FLAG));

        return scaledBitmap;
    }

    /**
     * ScalingLogic defines how scaling should be carried out if source and
     * destination image has different aspect ratio.
     *
     * CROP: Scales the image the minimum amount while making sure that at least
     * one of the two dimensions fit inside the requested destination area.
     * Parts of the source image will be cropped to realize this.
     *
     * FIT: Scales the image the minimum amount while making sure both
     * dimensions fit inside the requested destination area. The resulting
     * destination dimensions might be adjusted to a smaller size than
     * requested.
     */
    public static enum ScalingLogic {
        CROP, FIT
    }

    /**
     * Calculate optimal down-sampling factor given the dimensions of a source
     * image, the dimensions of a destination area and a scaling logic.
     *
     * @param srcWidth Width of source image
     * @param srcHeight Height of source image
     * @param dstWidth Width of destination area
     * @param dstHeight Height of destination area
     * @param scalingLogic Logic to use to avoid image stretching
     * @return Optimal down scaling sample size for decoding
     */
    public static int calculateSampleSize(int srcWidth, int srcHeight, int dstWidth, int dstHeight,
            ScalingLogic scalingLogic) {
        if (scalingLogic == ScalingLogic.FIT) {
            final float srcAspect = (float)srcWidth / (float)srcHeight;
            final float dstAspect = (float)dstWidth / (float)dstHeight;

            if (srcAspect > dstAspect) {
                return srcWidth / dstWidth;
            } else {
                return srcHeight / dstHeight;
            }
        } else {
            final float srcAspect = (float)srcWidth / (float)srcHeight;
            final float dstAspect = (float)dstWidth / (float)dstHeight;

            if (srcAspect > dstAspect) {
                return srcHeight / dstHeight;
            } else {
                return srcWidth / dstWidth;
            }
        }
    }

    /**
     * Calculates source rectangle for scaling bitmap
     *
     * @param srcWidth Width of source image
     * @param srcHeight Height of source image
     * @param dstWidth Width of destination area
     * @param dstHeight Height of destination area
     * @param scalingLogic Logic to use to avoid image stretching
     * @return Optimal source rectangle
     */
    public static Rect calculateSrcRect(int srcWidth, int srcHeight, int dstWidth, int dstHeight,
            ScalingLogic scalingLogic) {
        if (scalingLogic == ScalingLogic.CROP) {
            final float srcAspect = (float)srcWidth / (float)srcHeight;
            final float dstAspect = (float)dstWidth / (float)dstHeight;

            if (srcAspect > dstAspect) {
                final int srcRectWidth = (int)(srcHeight * dstAspect);
                final int srcRectLeft = (srcWidth - srcRectWidth) / 2;
                return new Rect(srcRectLeft, 0, srcRectLeft + srcRectWidth, srcHeight);
            } else {
                final int srcRectHeight = (int)(srcWidth / dstAspect);
                final int scrRectTop = (int)(srcHeight - srcRectHeight) / 2;
                return new Rect(0, scrRectTop, srcWidth, scrRectTop + srcRectHeight);
            }
        } else {
            return new Rect(0, 0, srcWidth, srcHeight);
        }
    }

    /**
     * Calculates destination rectangle for scaling bitmap
     *
     * @param srcWidth Width of source image
     * @param srcHeight Height of source image
     * @param dstWidth Width of destination area
     * @param dstHeight Height of destination area
     * @param scalingLogic Logic to use to avoid image stretching
     * @return Optimal destination rectangle
     */
    public static Rect calculateDstRect(int srcWidth, int srcHeight, int dstWidth, int dstHeight,
            ScalingLogic scalingLogic) {
        if (scalingLogic == ScalingLogic.FIT) {
            final float srcAspect = (float)srcWidth / (float)srcHeight;
            final float dstAspect = (float)dstWidth / (float)dstHeight;

            if (srcAspect > dstAspect) {
                return new Rect(0, 0, dstWidth, (int)(dstWidth / srcAspect));
            } else {
                return new Rect(0, 0, (int)(dstHeight * srcAspect), dstHeight);
            }
        } else {
            return new Rect(0, 0, dstWidth, dstHeight);
        }
    }


}

并在您的函数中使用此类,如下所示

public void onPicTaken(byte[] data) {

    if (data != null) {
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        int screenHeight = getResources().getDisplayMetrics().heightPixels;
        Bitmap bm = BitmapFactory.decodeByteArray(data, 0, (data != null) ? data.length : 0);

        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            // Notice that width and height are reversed
            Bitmap scaled = ScalingUtilities.createScaledBitmap(bm, screenHeight, screenWidth, ScalingLogic.FIT);
            int w = scaled.getWidth();
            int h = scaled.getHeight();
            // Setting post rotate to 90
            Matrix mtx = new Matrix();
            mtx.postRotate(90);
            // Rotating Bitmap
            bm = Bitmap.createBitmap(scaled, 0, 0, w, h, mtx, true);
        }else{// LANDSCAPE MODE
            //No need to reverse width and height
            Bitmap scaled = ScalingUtilities.createScaledBitmap(bm, screenHeight, screenWidth, ScalingLogic.FIT);
            bm=scaled;
        }
        ivCaptureImagePreview.setImageBitmap(bm);
        ivCaptureImagePreview.setVisibility(View.VISIBLE);
    }

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

保存在 ImageView 中时,从自定义相机拍摄的图像会被拉伸 的相关文章

随机推荐

  • Spring Integration 中的 @Router 与注释(请求/回复)

    您能提供在 Spring Integration 中路由消息的任何示例吗 按有效负载消息 标头或类似以下内容进行过滤
  • 将 -1 作为文件描述符传递给 mmap

    我对 FC17 Linux 中的 ls 命令进行了 strace 以下是输出 execve usr bin ls ls 48 vars 0 brk 0 0x27c1000 mmap NULL 4096 PROT READ PROT WRIT
  • 3D 数学:根据“向上”和“向上”正交向量计算倾斜(滚动)角度

    我希望这是提出这个问题的正确位置和这个一样 https stackoverflow com questions 3035590 bank angle from up vector and look at vector 但表示为纯数学而不是图
  • 隐式强制转换对委托类型推断的意外影响

    我有一个简单的Money带有隐式转换的类型decimal struct Money decimal innerValue public static implicit operator Money decimal value return
  • 在 Applescript 中监控 Spotify 曲目变化?

    我正在尝试找出通过 Spotify 的 Applescript 库检测曲目更改的最佳方法 到目前为止 我已经尝试检查玩家位置 如果它等于 0 则它是一个新曲目 并且咆哮通知会再次出现 如果有人重新开始一首歌等 这通常不起作用 我想知道是否更
  • 为什么复制构造函数会有多个参数?

    12 8 2 非模板构造函数 对于类 X 是一个复制构造函数 如果 它的第一个参数是 X 类型 const X 易失性 X 或 const 易失性 X 并且要么没有 其他参数或其他所有 参数有默认参数 8 3 6 106 到目前为止 我还没
  • 似乎找不到循环 PL/SQL 数组的方法?

    我正在尝试这样做 arrCauses APEX UTIL STRING TO TABLE P1 CAUSE FOR c IN 1 arrCauses count LOOP INSERT INTO DT EVENT CAUSE EVENT I
  • 量角器未连接到 DevTools

    当我的页面从 Protractor 运行时 如何使用 Chrome 开发者工具来检查它 当我尝试打开开发工具时 我从量角器收到此错误 UnknownError disconnected not connected to DevTools S
  • 如何设置 1dCNN+LSTM 网络(Keras)的输入形状?

    我有以下想法要实施 Input gt CNN gt LSTM gt Dense gt Output 输入有 100 个时间步长 每个步长有一个 64 维特征向量 A Conv1D层将在每个时间步提取特征 CNN 层包含 64 个滤波器 每个
  • 在自定义 UITableView 中显示空白 UITableViewCell

    我正在尝试自定义 UITableView 到目前为止 看起来不错 但是当我使用自定义 UITableViewCell 子类时 当只有 3 个单元格时 我不会得到空白表格单元格 替代文本 http img193 imageshack us i
  • 如何在 Swift 2.0 中将结构保存到 NSUserDefaults

    我有一个名为Jar我想将它们的数组保存到 NSUserDefaults 中 这是 jar 结构代码 struct Jar let name String let amount Int init name String amount Int
  • Apache Tomahawk 文件上传不工作

    我在使用 Apache Tomahawk 时遇到问题 Glassfish 3 0 1 不断记录 警告 JSF1064 无法从库 org apache myfaces custom 中找到或提供资源 inputFileUpload xhtml
  • 如何从我的应用程序打开“设置”应用程序? [复制]

    这个问题在这里已经有答案了 在我正在开发的 iPhone 应用程序中 用户需要通过设置应用程序输入一些配置 然后我的应用程序才能连接到服务器并运行 现在 当用户首次启动我的应用程序时 我会显示一条警报 解释用户应该转到设置 输入配置详细信息
  • 在打字稿中读取和写入文本文件

    我应该如何从 Node js 中的 TypeScript 读取和写入文本文件 我不确定是否会在 node js 中读 写沙箱文件 如果没有 我相信应该有一种访问文件系统的方法 相信应该有一种访问文件系统的方法 Include node d
  • 将 SQL 读取到 DataSet 到 XmlDocument

    下面的代码工作起来很梦幻 但它能变得更紧凑 更接近 C 风格吗 尤其是我对两个问题有怀疑 是不是很丑 老C式 填充fill通过将变量用作参数内 代码可以变得更紧凑而不是通过String C String connectionString s
  • Android TableLayout 宽度

    我有两列TableLayout作为滚动视图的唯一子视图 第一列包含TextViews labels 并且第二列包含EditText Spinner DateWidget等等 价值观 尽管我已指定android layout width fi
  • 列出 C 常量/宏

    有没有办法使GNU C 预处理器 cpp 或其他一些工具 列出给定点上的所有可用宏及其值C file 我正在寻找特定于系统的宏 同时移植一个已经精通 UNIX 的程序并加载一堆稀疏的 UNIX 系统文件 只是想知道是否有比寻找定义更简单的方
  • 最近的 Facebook API 的 FQLQuery

    我下载了最新的 Facebook PHP SDK 当我想要获取有关帖子的信息 例如点赞数 评论数和分享数 时 我的查询可以正常工作 但是 当我想获取用户的好友数量时 它不起作用并告诉我 Facebook FacebookAuthorizat
  • 将列表元素分组到字典中

    我有一个包含 8 个元素的列表 ConfigFile ControllerList 该列表的类型为 List
  • 保存在 ImageView 中时,从自定义相机拍摄的图像会被拉伸

    我正在使用此代码在 Imageview 中保存图片 但在 imageview 中保存时图像被拉伸 相机预览是完美的 单击右侧图像 但是当我在 imageview 中设置该图像时 图像被拉伸 public void onPicTaken by