c - 放大未压缩的 BMP

标签 c unix bmp

我正在处理这项作业,但出于某种原因,它没有复制所有行。它会跳过 bmp 的某些行,因此不会完全放大图片。 我将不胜感激一些关于为什么这样做的反馈。 我知道它必须与指针算法有关。

int enlarge(PIXEL* original, int rows, int cols, int scale, 
        PIXEL** new, int* newrows, int* newcols) 
{
    *newcols = cols * scale;
    *newrows = rows * scale;


    /* Allocate memory for enlarged bmp */ 
    *new = (PIXEL*)malloc( (*newrows)*(*newcols) * sizeof(PIXEL));
    if(!*new)
    {
        free(*new);
        fprintf(stderr, "Could not allocate memory.\n");
        return 1;
    }

    int i,j,k,l;
    int index = 0;
    int counter = scale*rows;
    PIXEL* o;
    PIXEL* n;


    for(i = 0; i < rows; i++)
    {
        for(j = 0; j < cols; j++)
        {

            for(k = 0; k < scale; k++)
            {

                o = original + (i*cols) + j;
                index++;
                for(l = 0; l < scale; l++)
                {
                    n = (*new) + ( i*cols*scale ) + index + (counter*l);
                    *n = *o;
                }

            }
        }
    }

    return 0;
}

最佳答案

您正在将一个正方形像素 block 复制到您的整数缩放图像中。外面的两个循环和您对原始像素地址的计算都没有问题。

现在,看看内部的两个循环,counterindex 发生了奇怪的事情,这不太合理。让我们重写一下。您需要做的就是为每一行复制一组像素。

o = original + i*cols + j;
n = *new + (i*cols + j) * scale;

for(sy = 0; sy < scale; sy++)
{
    for(sx = 0; sx < scale; sx++)
    {
        n[sy*cols*scale + sx] = *o;
    }
}

我真的不喜欢像 ijkl 这样的变量。它很懒惰,没有任何意义。很难看出 k 是行索引还是列索引。所以我使用 sxsy 来表示“缩放的 x 和 y 坐标”(我建议使用 xy 而不是 ji 但我保留了它们原样)。


现在,这是一个更好的方法。复制扫描线中的像素,而不是跳来跳去地写入单个缩放 block 。在这里,您缩放一行,并多次执行此操作。你可以用这个替换你的四个循环:

int srows = rows * scale;
int scols = cols * scale;

for( sy = 0; sy < srows; sy++ )
{
    y = sy / scale;
    o = original + y * cols;
    n = *new + sy * scols;

    for( x = 0; x < cols; x++ ) {
        for( i = 0; i < scale; i++ ) {
            *n++ = *o;
        }
        *o++;
    }
}

关于c - 放大未压缩的 BMP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19552769/

相关文章:

java - 在java中将PPM转换为JPG或BMP

c - 将值分类到适当的组中 : Counter Arrays

c++ - 如何在 Makefile 中向 1 头文件添加引用

c - C语言中的pipe 2 linux命令

c - 检测C中的大小写

linux - ash 文件的结构如何?

python - Bash 与 Perl/Python : OS call perfomace

windows - NSBitmapImageRep生成的BMP无法在Windows上读取

node.js - 如何区分 Node.js 中的 UNIX 套接字连接?

c++ - 读取bmp文件中的像素值