Ir ao conteúdo
  • Cadastre-se

matheus.Matta

Membro Júnior
  • Posts

    17
  • Cadastrado em

  • Última visita

Reputação

17
  1. @arfneto algumas coisas ainda tenho que entender por exemplo o a alocação de memória, mas com o tempo e pratica vou acaba entendendo.
  2. @arfneto marquei como solução sua ultima resposta, acho que n precisamos mais de nada so apenas o bom estudo. vou procurar entender cada aspecto e imprimenta no meu codigo. você gostaria de receber o resultado ? ja aviso que deve demorar kkkk, ja que você me ensinou tanto gostaria de receber o seu feedback no final. o projeto consiste em criar um servidor em C com curl ou algo do tipo para criamos um site de edição. por que o C ? porque e difícil. acredito que fazendo algo desse nivel no C eu poderei fazer em qualquer lugar. n e para criar nada usavel ou super eficiente e apenas estudo, gosto de usar o C porque eu consigo entender a a origem da algo e isso e muito bom.
  3. @Midori brabo conseguiu entender o codigo rapaido kkkkkkkkkk eu demorei 2 semanas apenas
  4. @arfneto o que eu poderia fazer com o fread? para diminuir a carga. tambem me encontro em outro problema uso o imageMagick para coverte para bmp o unico porém e que quando eu passo essa imagem convertida no C o arquivo se corrompe tem ideia do que possa ser ? @arfneto e tambem ainda precisaria usar algo para manipular os arquivos, tipo ler as imagem na pasta uplodas. o que você me recomenda a usar ?
  5. @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:
  6. @arfneto @Midori GRAÇAS A AJUDA DE vocês EU FINALMENTE CONSEGUI, PROCUREI ENTENDER COMO MANIPULAR O BMP, CRIEI MINHA PROPRIA LIB PARA MANIPULAR ( vou deixa o codigo abaixo ) E FUNCIONOU PREFEITAMENTE. Vídeo do resultado: #include "myBmp.h" #include <stdio.h> #include <stdlib.h> int main() { const char* filename = "lenna.bmp"; IMG_TAM t = pegarTamanho(filename); int l = t.qtdLinhas; int c = t.qtdColunas; //alocação de imagem int** R = (int**)malloc(sizeof(int*) * l); int** G = (int**)malloc(sizeof(int*) * l); int** B = (int**)malloc(sizeof(int*) * l); for (int i = 0; i < l; i++) { R[i] = (int*)malloc(sizeof(int) * c); G[i] = (int*)malloc(sizeof(int) * c); B[i] = (int*)malloc(sizeof(int) * c); } carregaImagem(filename, R, G, B, c, l); for (int i = 0; i < l; i++) { for (int j = 0; j < c; j++) { // Calcule a média dos componentes de cor R, G e B int grayValue = (R[i][j] + G[i][j] + B[i][j]) / 3; // Atribua o valor médio a cada componente de cor R[i][j] = grayValue; G[i][j] = grayValue; B[i][j] = grayValue; } } salvaImagem("saida.bmp", R, G, B, c, l); // liberar o espaço da memória for (int i = 0; i < l; i++) { free(R[i]); free(G[i]); free(B[i]); } free(R); free(G); free(B); return 0; } //myBmp.c----------------------------------------------- #include "myBmp.h" #include <stdio.h> #include <stdlib.h> // Implementação da função para carregar uma imagem BMP void carregaImagem(const char* filename, int** R, int** G, int** B, int width, int height) { FILE* file = fopen(filename, "rb"); if (file == NULL) { printf("Erro ao abrir o arquivo BMP.\n"); return; } BMPFileHeader fileHeader; BMPInfoHeader infoHeader; fread(&fileHeader, sizeof(BMPFileHeader), 1, file); fread(&infoHeader, sizeof(BMPInfoHeader), 1, file); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { fread(&B[i][j], 1, 1, file); fread(&G[i][j], 1, 1, file); fread(&R[i][j], 1, 1, file); } } fclose(file); } // Implementação da função para salvar uma imagem BMP void salvaImagem(const char* filename, int** R, int** G, int** B, int width, int height) { FILE* file = fopen(filename, "wb"); if (file == NULL) { printf("Erro ao criar o arquivo BMP de saída.\n"); return; } BMPFileHeader fileHeader; BMPInfoHeader infoHeader; // Preencha os campos de fileHeader e infoHeader com os valores apropriados // Certifique-se de que esses valores correspondam às dimensões e ao formato da imagem BMP que você está criando fwrite(&fileHeader, sizeof(BMPFileHeader), 1, file); fwrite(&infoHeader, sizeof(BMPInfoHeader), 1, file); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { fwrite(&B[i][j], 1, 1, file); fwrite(&G[i][j], 1, 1, file); fwrite(&R[i][j], 1, 1, file); } } fclose(file); } IMG_TAM pegarTamanho(const char* filename) { FILE* file = fopen(filename, "rb"); if (file == NULL) { printf("Erro ao abrir o arquivo BMP.\n"); exit(1); } // Leitura do cabeçalho BMP para obter as dimensões da imagem BMPFileHeader fileHeader; BMPInfoHeader infoHeader; fread(&fileHeader, sizeof(BMPFileHeader), 1, file); fread(&infoHeader, sizeof(BMPInfoHeader), 1, file); IMG_TAM tamanho; tamanho.qtdLinhas = infoHeader.imageHeight; tamanho.qtdColunas = infoHeader.imageWidth; fclose(file); return tamanho; } //myBmp.h----------------------------------------------------- #ifndef MYBMP_H #define MYBMP_H #pragma pack(1) typedef struct { int qtdLinhas; int qtdColunas; } IMG_TAM; typedef struct { char signature[2]; int fileSize; int reserved; int dataOffset; } BMPFileHeader; typedef struct { int headerSize; int imageWidth; int imageHeight; short planes; short bitsPerPixel; int compression; int imageSize; int xPixelsPerMeter; int yPixelsPerMeter; int colorsUsed; int importantColors; } BMPInfoHeader; // Declaração das funções IMG_TAM pegarTamanho(const char* filename); void carregaImagem(const char* filename, int** R, int** G, int** B, int width, int height); void salvaImagem(const char* filename, int** R, int** G, int** B, int width, int height); #endif
  7. @arfneto agora entendi, parece que me falta conhecimento sobre o assunto. tem algum lugar que eu possa me aprofundar? melhor forma de enteder isso e eu criando a minha propria para manipular e n usar a que o proff disponibilizou. Na verdade ela foi criada para assinar matrix para os estudantes eu que estava querendo levar a um nivel diferente sem nescessidade, mas quando me vem a ideia n consigo parar ate fazer kkk
  8. a discusão aqui esta muito elevada para meu nivel KKKK, MAS Continuem esta me fazendo entender so estou confuso em uma coisa, no replit site que eu uso para estudo na faculdade esse mesmo codigo funciona sem problemas, vou deixar um Vídeo: EXPLICAÇÃO DO CODIGO: pegar uma imagem da pasta uploads e deixa em preto e branco obivo a img tem que estar em .bmp em um ambiente tipo esse do replit onde n gera um executavel funciona prefeitamente unico problema e que eu preciso de um executavel para continuar meu projeto onde eu vou criar uma especie de aplicador de filtros. tipo o que o instagram tem @Midori isso se ajeita no for onde eu declaro R[i][j] = G[i][j]; o filtro n e tão importante, isso e so um teste para tentar gerar um executavel.
  9. @arfneto você conhece alguma biblioteca parecida com essa que funcione ? pelo visto o problema esta sendo ela então e melhor troca-la. eu criei outro topico com uma explicação melhor se você puder olhar la e me ajuda kkk, você esta sendo minha unica esperança de terminar esse projeto. alias se eu habilitar o uso de VLA funcionaria de alguma forma ?
  10. @arfneto não acredito que o erro seja de sintaxe ja que o codigo roda prefeitamente no replit, o problema e quando eu passo o codigo para outro programa tipo vscode a libs n fui eu que crie apenas uso para editar as imagens que tem que ser em formato bmp
  11. 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: VOU DEIXAR UM Vídeo DO ERRO NO LINK PARA O YOUTUBE AQUI: https://www.youtube.com/watch?v=SRXG-AQkps0&ab_channel=MatheusEduardo
  12. @arfneto claro amigo eu posto o codigo sim, mais e meio grande. main.c <code> #include <dirent.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "libbmp.h" #include "imghelpers.h" #define MYERR(...) do { \ printf ("ERROR @ %s %s (%d): ", __FILE__,__func__,__LINE__); \ printf (__VA_ARGS__); \ } while (0) int main() { DIR *dp; struct dirent *ep; char filename[300]; int firstFile = 0; const char directory[] = "uploads/"; 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; printf("sucesso arquivo encontrado"); } } (void)closedir(dp); } else { perror("Não foi possível abrir o diretório 'uploads'"); return 1; } printf("\n"); printf("%s",filename); 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); 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]; } printf("%d",i); } salvaImagem(t, R, G, B, filename); mostrarNoReplit(filename); printf("img editada"); return 0; } <code> agora eu possu duas pasta de codigo diferente uma .h e outra .c libbmp.h e libbmp.c <code> #ifndef __LIBBMP_H__ #define __LIBBMP_H__ #include <stdio.h> #define BMP_MAGIC 19778 #define BMP_GET_PADDING(a) ((a) % 4) enum bmp_error { BMP_FILE_NOT_OPENED = -4, BMP_HEADER_NOT_INITIALIZED, BMP_INVALID_FILE, BMP_ERROR, BMP_OK = 0 }; 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; #define BMP_PIXEL(r, g, b) ((bmp_pixel){(b), (g), (r)}) 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__ */ <code> //fim---------------- <code> #include <stdio.h> #include <stdlib.h> #include "libbmp.h" 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; } <code> agora a mesma coisa com o imghelpers.h e .c <code> #ifndef IMGPHELPERS_H #define IMGPHELPERS_H #include <stdio.h> 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 <code> //fim ----------- <code> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "libbmp.h" #include "imghelpers.h" int limit(int x) { if (x > 255) return 255; else if (x < 0) return 0; else return x; } IMG_TAM pegarTamanho(const char *filename) { FILE *f = fopen(filename, "rb"); if (f == NULL) { printf("arquivo %s não existe!\n", filename); exit(1); } fclose(f); IMG_TAM t; bmp_img img; bmp_img_read(&img, filename); t.qtdColunas = img.img_header.biWidth; t.qtdLinhas = img.img_header.biHeight; bmp_img_free(&img); return t; } 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) { bmp_img img; bmp_img_read(&img, filename); int width = t.qtdColunas; int height = t.qtdLinhas; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { R[y][x] = img.img_pixels[y][x].red; G[y][x] = img.img_pixels[y][x].green; B[y][x] = img.img_pixels[y][x].blue; } } printf("- - Imagem %s carregada com %dx%d px - -\n", filename, width, height); } 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) { bmp_img img; int width = t.qtdColunas; int height = t.qtdLinhas; bmp_img_init_df(&img, width, height); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { bmp_pixel_init(&img.img_pixels[y][x], limit(R[y][x]), limit(G[y][x]), limit(B[y][x])); } } bmp_img_write(&img, filename); bmp_img_free(&img); printf("- - Imagem salva no caminho %s - -\n", filename); } void zerarPixels( IMG_TAM t, unsigned char PIX[t.qtdLinhas][t.qtdColunas]) { for (int y = 0; y < t.qtdColunas; y++) { for (int x = 0; x < t.qtdLinhas; x++) { PIX[x][y] = 0; } } } void mostrarNoReplit(const char *filename) { int buffsize = 256; char buf[buffsize]; char fehString[] = "feh --full-screen --auto-zoom %s > /dev/null 2>&1"; int filename_length = strlen(filename); int fehString_length = strlen(fehString); if (filename_length + fehString_length > buffsize) { return; } printf("Exibindo imagem: %s", filename); fflush(stdout); snprintf(buf, sizeof buf, fehString, filename); system(buf); } <code> o codigo deve pegar a primeira imagem da pasta uploads e editala deixando em preto e branco o codigo encontra a imagem so que na hora que vai usar a biblioteca o codigo morre n e faz nada usei o seguinte codigo para compilar gcc main.c libbmp.c imghelpers.c -o main.exe
  13. @devair1010 OLÁ, não fui eu que criei infelizmente, mas vou postar o projeto assim que esta pronto. mas ate então preciso compilar e n posso por ela na pasta main. queria compilar a biblioteca junto.
  14. procure verificar a versão do game e atualizar, tambem va na steam entre na propiedades do game e clique em verificar integridade dos arquivos. caso nada funcione vai te restar desinstalar e instalar
  15. ola gostaria de saber como compilo arquivo C que contenha uma biblioteca .h por exemplo libbmp.h queeu uso para editar. MEU CODIGO ESTA AQUi: https://replit.com/@MatheusEduard48/MatrizIMG-1#main.c eu tento pelo shell mas da erro sempre n sei porque

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...

 

GRÁTIS: ebook Redes Wi-Fi – 2ª Edição

EBOOK GRÁTIS!

CLIQUE AQUI E BAIXE AGORA MESMO!