更改像素的颜色而不使用C中的 'graphics.h'库

标签 c pointers file-io

我需要学习这些东西才能通过考试,所以 我尝试了这段代码,但没有成功。我怎样才能让它工作?

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <math.h>
#include "img_header.h"   

('img_header.h'包含一些函数)

void simple_rgb_image_init(Simple_RGB_Image* sink, int32_t  width, int32_t  height);


typedef struct {
int32_t width;
int32_t height;
uint8_t* data;
} Simple_RGB_Image;


int main()
{

Simple_RGB_Image img;
int32_t width = 3;
int32_t height = 3;
FILE* out_file;

int32_t w;
int32_t x,y ;

uint8_t red,green,blue;

uint8_t* p_red;
uint8_t* p_green;
uint8_t* p_blue;

p_red   = &red;
p_green = &green;
p_blue  = &blue;

simple_rgb_image_init(&img,width,height);  

x = 1 ;
y = 1 ;
w = calculate_stride(width);   //calculate the stride

blue  = img.data[3 *(w*y + x) + 0];
green = img.data[3 *(w*y + x) + 1];
red   = img.data[3 *(w*y + x) + 3];

printf("blue = %i \n" , blue);  //205
printf("green = %i \n" , green);//205
printf("red = %i \n" , red);    //205

printf("\n\n");

*p_red   = 0;
*p_green = 0;
*p_blue  = 255;

printf("blue = %i \n" , blue);  //255
printf("green = %i \n" , green);//0
printf("red = %i \n" , red);    //0


out_file = fopen("My_picture.bmp","wb");
simple_rgb_image_to_bitmap_stream(&img,out_file); //save the picture as a Bitmap file
fclose(out_file);
simple_rgb_image_clear(&img); //Free memory



return 0;
}


void simple_rgb_image_init(Simple_RGB_Image* sink, int32_t  width, int32_t  height)
{
sink->width = width;
sink->height = height;
sink->data = (uint8_t*)malloc(3 * width * height);
}
<小时/>

我确实直接处理了指针,但是徒劳无功!该代码仍然生成一个 9 像素位图图像,颜色为(红色 = 205,蓝色 = 205,绿色 = 205),这似乎是一个奇怪的结果,因为当我编译代码时,它打印出以下内容:

blue = 0
green = 72
red = 45 

blue = 255
green = 0 
red = 0 

Press any key to continue . . . 

代码是:

p_blue  = &(img.data[3 *(w*y + x) + 0]);
p_green = &(img.data[3 *(w*y + x) + 1]);
p_red   = &(img.data[3 *(w*y + x) + 2]);

printf("blue = %i \n" , *p_blue);  
printf("green = %i \n" , *p_green);
printf("red = %i \n" , *p_red);    

printf("\n\n");

*p_red   = 0;
*p_green = 0;
*p_blue  = 255;

printf("blue = %i \n" , *p_blue);  
printf("green = %i \n" , *p_green);
printf("red = %i \n" , *p_red);    

最佳答案

这里的问题是,您正在更改局部变量redgreenblue。这些变化不会反射(reflect)在 img 内部。

相反,摆脱这些局部变量并直接处理指针,例如

p_blue  = &(img.data[3 *(w*y + x) + 0]);
p_green = &(img.data[3 *(w*y + x) + 1]);
p_red   = &(img.data[3 *(w*y + x) + 3]);  //are you sure, this is 3. not 2?

然后,如果你这样做

*p_red   = 0;
*p_green = 0;
*p_blue  = 255;

它将反射(reflect)在img中。

也就是说,请do not cast Cmalloc() 及其族的返回值。

关于更改像素的颜色而不使用C中的 'graphics.h'库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30786555/

相关文章:

c++ - 打开目录中的文件夹

pointers - 无法正确取消引用指针并从内存地址数组中获取实际值

c - 自动微分Matlab Coder生成的C代码

C 结构指针和作用域混淆

编译器执行顺序

c - 是否可以在函数内部分配数组并使用引用返回它?

c++ - 确定动态内存分配中 char 指针的最大容量

c - 在 ENOSPC 之后写入描述符是否安全

ruby - 如何在 Ruby 中处理大文件?

Java:jsch.put 后​​无法删除本地文件