![](/img/trans.png)
[英]Generate a “pieslice” in C without using the pieslice() of graphics.h
[英]Change color of a pixel without using 'graphics.h' library in C
為了通過考試,我需要學習這些內容,所以我嘗試了此代碼,但沒有用。 我如何使它工作?
#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);
這里的問題是,您正在更改局部變量red
, green
, blue
。 這些變化沒有反映在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;
它將反映在img
。
也就是說,請不要在C
中malloc()
和family的返回值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.