Ir ao conteúdo

Posts recomendados

Postado

Estou com um problema ao executar um main.exe, usando o trabalho de filtro que você passou criei um executável para deixar uma img em preto e branco,
Fiz isso apenas para testar  e aprender a compilar já que só usamos replit.
mas o código não funciona, pelo que entendi que as duas libs( libbmp.h e imghelpers.h ) elas não funcionam.
descrição do código:
O programa serve para pegar a primeira imagem do arquivo uploads e deixá-la em preto e branco. 

descrição do problema:
o programa acha o diretório e pega a primeira imagem >lenna.bmp< e atribui no filename da seguinte forma snprintf(filename, sizeof(filename), "%s%s", directory, ep->d_name); o filename fica assim uploads/lenna.bmp. após isso ao chega na parte das libs onde ocorrerá a edição e o programa  morre e finaliza. isso me leva a crer que o problema está nas libs ou na minha compilação. 


código usado para compilar:

 gcc main.c libbmp.c imghelpers.c -o main.exe -o 

print dos arquivos:
image.png.6f8b743431669ed37c3322747e01bd62.png

 VOU DEIXAR UM Vídeo DO ERRO NO LINK PARA O YOUTUBE AQUI: https://www.youtube.com/watch?v=SRXG-AQkps0&ab_channel=MatheusEduardo

 

  • Curtir 1
Postado

@matheus.Matta     para essas libs "HEADER"  funcionar elas precisam  estar na mesma pasta onde você coloca esse código da função main , seu código principaL , 

aqui a função     "main.c"

#define     _WIN32_WINNT 0x600
#define     _h GetStdHandle(STD_OUTPUT_HANDLE)
#include    <stdio.h>
#include    <conio.h>
#include    <iso646.h>
#include    <stdlib.h>
#include    <string.h>
#include    <windows.h>
#include    <math.h>
#include    <time.h>
#include    <locale.h>
#include    <dirent.h>
#include    "libbmp.h"
#include    "imghelpers.h"
#include    "libbmp.c"
#include    "imghelpers.c"
int main    ( int argc, char *argv[]                         )
{
    int letra,fundo;
    CONSOLE_SCREEN_BUFFER_INFO _c                            ;
    if( GetConsoleScreenBufferInfo     ( _h, & _c )          )
    {
        letra = (   _c.wAttributes & 0xFF )            & 0x0F;
        fundo = ( ( _c.wAttributes & 0xFF ) >> 4    )  & 0x0F;
    }
    SetConsoleTextAttribute( _h, 11 +       ( 0 << 4 )      );
    setlocale(LC_ALL,"");
    ///-------------------------------------------------------

    DIR *dp;
    struct dirent *ep;
    char filename[100];
    int firstFile = 0;                   // Variável de controle
    const char directory[] = "uploads/"; // Caminho do diretório
    int ret = 0;
    dp = opendir(directory);
    if (dp != NULL)
    {
        while ((ep = readdir(dp)))
        {
            if (ep->d_type == DT_REG && !firstFile)
            {
                snprintf(filename, sizeof(filename), "%s%s", directory, ep->d_name);
                firstFile = 1;
            }
        }
        (void)closedir(dp);
    }
    else
    {
        SetConsoleTextAttribute( _h, 15 +  ( 12 << 4 )  );
        perror("\n  Não foi possível abrir o diretório 'uploads'.  !  ");
        ret = 1;
    }
    if( ! ret )
    {
        // Utilize apenas imagens .bmp com o formato 24 (true color)
        // converta em: https://online-converting.com/image/convert2bmp/
        bmp_img img;
        printf("\n");
        IMG_TAM t = pegarTamanho(filename);
        int l = t.qtdLinhas, c = t.qtdColunas;
        int R[l][c];
        int G[l][c];
        int B[l][c];
        carregaImagem(t, R, G, B, filename);
        // manipule sua imagem aqui.
        for (int i = 0; i < l; i++)
        {
            for (int j = 0; j < c; j++)
            {
                R[i][j] = G[i][j];
                B[i][j] = R[i][j];
                G[i][j] = B[i][j];
            }
        }
        salvaImagem(t, R, G, B, filename);
        mostrarNoReplit(filename);
    }
    ///------------------------------------------------------
    SetConsoleTextAttribute( _h, letra +  ( fundo << 4 )  );
    printf("\n\n\n");
    return    ret                                          ;
}

o código do "HEADER"   libbmp.h  :

#ifndef LIBBMP_H_INCLUDED
#define LIBBMP_H_INCLUDED

  #include <stdio.h>

#define BMP_MAGIC 19778
#define BMP_GET_PADDING(a) ((a) % 4)
#define BMP_PIXEL(r, g, b) ((bmp_pixel){(b), (g), (r)})
enum bmp_error
{
  BMP_FILE_NOT_OPENED = -4,
  BMP_HEADER_NOT_INITIALIZED,
  BMP_INVALID_FILE,
  BMP_ERROR,
  BMP_OK = 0
};
typedef struct ax as;
typedef struct _bmp_header
{
  unsigned int bfSize;
  unsigned int bfReserved;
  unsigned int bfOffBits;
  unsigned int biSize;
  int biWidth;
  int biHeight;
  unsigned short biPlanes;
  unsigned short biBitCount;
  unsigned int biCompression;
  unsigned int biSizeImage;
  int biXPelsPerMeter;
  int biYPelsPerMeter;
  unsigned int biClrUsed;
  unsigned int biClrImportant;
} bmp_header;
typedef struct _bmp_pixel
{
  unsigned char blue;
  unsigned char green;
  unsigned char red;
} bmp_pixel;

typedef struct _bmp_img
{
  bmp_header* img_header;
  bmp_pixel **img_pixels;
} bmp_img;
void bmp_header_init_df        (bmp_header*, const int, const int);
enum bmp_error bmp_header_write(const bmp_header*, FILE*         );
enum bmp_error bmp_header_read (bmp_header*, FILE*               );
void bmp_pixel_init            (bmp_pixel*, const unsigned char   ,
                                const unsigned char, const unsigned char);
void bmp_img_alloc             (bmp_img*                         );
void bmp_img_init_df           (bmp_img*, const int, const int   );
void bmp_img_free              (bmp_img*                         );
enum bmp_error bmp_img_write   (const bmp_img*, const char*      );
enum bmp_error bmp_img_read    (bmp_img*, const char*            );

#endif                         /// LIBBMP_H_INCLUDED

e o código do header   imghelpers :

#ifndef IMGHELPERS_H
#define IMGHELPERS_H
#include <stdio.h>
typedef struct IMG_TAM
{
  int qtdLinhas;
  int qtdColunas;
};
typedef struct IMG_TAM IMG_TAM;
IMG_TAM pegarTamanho(const char *filename);
void carregaImagem(
    IMG_TAM t,
    int R[t.qtdLinhas][t.qtdColunas],
    int G[t.qtdLinhas][t.qtdColunas],
    int B[t.qtdLinhas][t.qtdColunas],
    const char *filename);
void salvaImagem(
    IMG_TAM t,
    int R[t.qtdLinhas][t.qtdColunas],
    int G[t.qtdLinhas][t.qtdColunas],
    int B[t.qtdLinhas][t.qtdColunas],
    const char *filename);
void zerarPixels(
    IMG_TAM t,
    unsigned char PIX[t.qtdLinhas][t.qtdColunas]);
void mostrarNoReplit(const char *filename);

#endif                /// IMGPHELPERS_H_INCLUDED

e aqui o código da   libbmp. c  :

/// Aqui ColoQue O cOdigo Das FunCOes
void bmp_header_init_df(bmp_header *header, const int width, const int height)
{
    header->bfSize =
        (sizeof(bmp_pixel)  * width + BMP_GET_PADDING(width)) * abs(height);
    header->bfReserved      = 0;
    header->bfOffBits       = 54;
    header->biSize          = 40;
    header->biWidth         = width;
    header->biHeight        = height;
    header->biPlanes        = 1;
    header->biBitCount      = 24;
    header->biCompression   = 0;
    header->biSizeImage     = 0;
    header->biXPelsPerMeter = 0;
    header->biYPelsPerMeter = 0;
    header->biClrUsed       = 0;
    header->biClrImportant  = 0;
}
enum bmp_error bmp_header_write(const bmp_header *header, FILE *img_file)
{
    if (header == NULL)
    {
        return BMP_HEADER_NOT_INITIALIZED;
    }
    else if (img_file == NULL)
    {
        return BMP_FILE_NOT_OPENED;
    }
    const unsigned short magic = BMP_MAGIC;
    fwrite(&magic, sizeof(magic), 1, img_file);
    fwrite(header, sizeof(bmp_header), 1, img_file);
    return BMP_OK;
}
enum bmp_error bmp_header_read(bmp_header *header, FILE *img_file)
{
    if (img_file == NULL)
    {
        return BMP_FILE_NOT_OPENED;
    }
    unsigned short magic;
    if (fread(&magic, sizeof(magic), 1, img_file) != 1 || magic != BMP_MAGIC)
    {
        return BMP_INVALID_FILE;
    }
    if (fread(header, sizeof(bmp_header), 1, img_file) != 1)
    {
        return BMP_ERROR;
    }
    return BMP_OK;
}
void bmp_pixel_init(bmp_pixel *pxl, const unsigned char red,
                    const unsigned char green, const unsigned char blue)
{
    pxl->red   = red;
    pxl->green = green;
    pxl->blue  = blue;
}
void bmp_img_alloc(bmp_img *img)
{
    const
    size_t        h = abs(img->img_header->biHeight);
    img->img_pixels = malloc(sizeof(bmp_pixel *) * h);
    for (size_t y   = 0; y < h; y++)
    {
        img->img_pixels[y] = malloc(sizeof(bmp_pixel) * img->img_header->biWidth);
    }
}
void bmp_img_init_df(bmp_img *img, const int width, const int height)
{
    bmp_header_init_df(&img->img_header, width, height);
    bmp_img_alloc(img);
}
void bmp_img_free(bmp_img *img)
{
    const size_t h = abs(img->img_header->biHeight);
    for (size_t y = 0; y < h; y++)
    {
        free(img->img_pixels[y]);
    }
    free(img->img_pixels);
}
enum bmp_error bmp_img_write(const bmp_img *img, const char *filename)
{
    FILE *img_file = fopen(filename, "wb");
    if (img_file == NULL)
    {
        return BMP_FILE_NOT_OPENED;
    }
    const enum bmp_error err = bmp_header_write(&img->img_header, img_file);
    if (err != BMP_OK)
    {
        fclose(img_file);
        return err;
    }
    const size_t h = abs(img->img_header->biHeight);
    const size_t offset = (img->img_header->biHeight > 0 ? h - 1 : 0);
    const unsigned char padding[3] = {'\0', '\0', '\0'};
    for (size_t y = 0; y < h; y++)
    {
        fwrite(img->img_pixels[offset - y], sizeof(bmp_pixel),
               img->img_header->biWidth, img_file);
        fwrite(padding, sizeof(unsigned char),
               BMP_GET_PADDING(img->img_header->biWidth), img_file);
    }
    fclose(img_file);
    return BMP_OK;
}
enum bmp_error bmp_img_read(bmp_img *img, const char *filename)
{
    FILE *img_file = fopen(filename, "rb");
    if (img_file == NULL)
    {
        return BMP_FILE_NOT_OPENED;
    }
    const enum bmp_error err = bmp_header_read(&img->img_header, img_file);
    if (err != BMP_OK)
    {
        fclose(img_file);
        return err;
    }
    bmp_img_alloc(img);
    const size_t h       = abs(img->img_header->biHeight);
    const size_t offset  = (img->img_header->biHeight > 0 ? h - 1 : 0);
    const size_t padding = BMP_GET_PADDING(img->img_header->biWidth);
    const size_t items   = img->img_header->biWidth;
    for ( size_t y       = 0; y < h; y++)
    {
        if (fread(img->img_pixels[offset - y], sizeof(bmp_pixel), items,
                  img_file) != items)
        {
            fclose(img_file);
            return BMP_ERROR;
        }
        fseek(img_file, padding, SEEK_CUR);
    }
    fclose(img_file);
    return BMP_OK;
}

e o código da função     imghelpers.c   :

/// Aqui ColoQue Os cOdigo Das FunCOes

typedef struct bmp_img;
typedef struct IMG_TAM;
typedef bmp_img;
IMG_TAM pegarTamanho(const char *filename)
{
    /// coloque o cOdigo Aqui, o q voce quer q ele faCa .
    printf("Você não tinhA essa FuCAo . !\n");
    return;
}
void salvaImagem /// funCAo salvar imagem
(IMG_TAM t, int R[t.qtdLinhas][t.qtdColunas],
 int G[t.qtdLinhas][t.qtdColunas],
 int B[t.qtdLinhas][t.qtdColunas],
 const char *filename)
{
    /// coloque o cOdigo Aqui, o q voce quer q ele faCa .
    return;
}
void mostrarNoReplit(const char *filename)
{
    return;
}
void carregaImagem(
    IMG_TAM t,
    int R[t.qtdLinhas][t.qtdColunas],
    int G[t.qtdLinhas][t.qtdColunas],
    int B[t.qtdLinhas][t.qtdColunas],
    const char *filename)
{
    /// coloque o cOdigo Aqui, o q voce quer q ele faCa .
    return;
}

porém essas funções que fazem as modificações nas imagens , não estão prontas , pois falta exatamente um código para fazer tais modificações .

Postado

@matheus.Matta testei aqui e funcionando "normal"!

funcionando.thumb.png.60a2ef9a4d45d6da448469574069859b.png

O replit funciona com uma maquina virtual linux, então você precisa de um ambiente igual ao replit para funcionar.

 

a maioria das versões do gcc para o windows não ligam para a compatibilidade entre os sistemas, então seu problema seja esse.

recomendo usar o tdm-gcc pelo fato de ser bem mais simples pra quem está iniciando.

  • Curtir 1
Postado

@kgin então meu problema era eu usar windows ??? kkk bem eu criei outro codigo e funcionou no windows tranquilo. mas eu uso o C no vscode então n sei muito o que dizer sobre isso. 

@kgin aqui um Vídeo do novo codigo: 

 

  • Curtir 1
Postado
4 horas atrás, matheus.Matta disse:

então meu problema era eu usar windows

 

Não, não era com o Windows. O programa não estava bom, a biblioteca também não.

Mas o problema era que precisava habilitar uma extensão ao compilar para aceitar os VLA que sua biblioteca havia declarado. E se usa Windows precisava naquela versão instalar também um clone de dirent.h para Windows porque essa é uma biblioteca Unix nativa.

  • Obrigado 1

Crie uma conta ou entre para comentar

Você precisa ser um usuário para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar agora

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...

LANÇAMENTO!

eletronica2025-popup.jpg


CLIQUE AQUI E BAIXE AGORA MESMO!