You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现多维数组元素倍增函数 完成图像按指定倍数等比例放大

实现思路

你需要的是基于像素块复制的图像放大能力(属于最近邻插值放大的最简场景),核心逻辑是把原图像的每个像素,扩展为multiply × multiply大小的同值像素块:

  • 先做入参合法性校验:multiply必须是≥1的正整数,originalImage不能为null且长宽不能为0
  • 计算新图像尺寸:新行数 = 原行数 × 放大倍数,新列数 = 原列数 × 放大倍数
  • 遍历原图像的每个像素点,将其对应到新图像里的multiply × multiply区块,全部填充为当前原像素的值

代码实现

public int[,] Multiply(int[,] originalImage, int multiply)
{
    // 入参合法性校验
    if (originalImage == null)
        throw new ArgumentNullException(nameof(originalImage));
    if (multiply < 1)
        throw new ArgumentOutOfRangeException(nameof(multiply), "放大倍数必须是正整数");
    
    int originalRows = originalImage.GetLength(0);
    int originalCols = originalImage.GetLength(1);
    if (originalRows == 0 || originalCols == 0)
        return new int[0, 0];

    // 初始化放大后的新数组
    int newRows = originalRows * multiply;
    int newCols = originalCols * multiply;
    int[,] result = new int[newRows, newCols];

    // 遍历原像素填充对应区块
    for (int i = 0; i < originalRows; i++)
    {
        for (int j = 0; j < originalCols; j++)
        {
            int currentPixel = originalImage[i, j];
            // 填充当前像素对应的multiply*multiply大小的块
            for (int rowOffset = 0; rowOffset < multiply; rowOffset++)
            {
                for (int colOffset = 0; colOffset < multiply; colOffset++)
                {
                    result[i * multiply + rowOffset, j * multiply + colOffset] = currentPixel;
                }
            }
        }
    }

    return result;
}

你给出的示例传入multiply=2调用该函数,输出结果和你贴的预期数组完全一致。

内容的提问来源于stack exchange,提问作者ChristianLe87

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 13:39:00