2014-09-04 3 views
2

Прежде всего, привет там!Создание БОЛЬШИХ изображений

затем, немного контекста:

Я на самом деле работает над «Maze генератора». На данный момент я могу создать лабиринты с шириной 18500 и высотой 18500 (что делает меня счастливым !!).

Итак, никаких проблем с генерацией.

Тогда, конечно, я хотел записать их в файлы .jpeg/.bmp или еще.

Итак, для лабиринта 18k5 * 18k5 мне нужно изображение 37k * 37k.

Я сначала пробовал с .jpeg. Это сработало, но выходные файлы были 1.2 GigaBytes большие. У них слишком много времени ... но я могу их открыть.

Поэтому я попытался использовать формат BMP, потому что он позволяет кодировать пиксели по 1 бит каждый. Выходные файлы теперь значительно меньше ... но я не могу их открыть ... Я говорю, что файлы «повреждены или слишком большие».

Я не думаю, что они повреждены, потому что они работали с лабиринтом 10k * 10k (20k * 20k), и он не смог открыть с таким же кодом лабиринт 13k * 13k (26k * 26k изображение).

Так вот код (я использую EasyBMP ОМТ):

int    main() 
{ 
    HandyMaze   labz(MAZE_SIDE, MAZE_SIDE); // Maze generator 
    Labz*    l;       // Maze iteself 
    BMP    img; 

    if (labz.Generate() == false) 
    { 
     std::cout << "Derp" << std::endl; 
     return (1); 
    } 
    l = labz.GetFormatedLab(); 
    if (l == 0) 
    { 
     std::cout << "Dorp" << std::endl; 
     return (1); 
    } 
    std::cout << "Generated" << std::endl; 
    std::cout << "Creating Image ..." << std::endl; 
    img.SetSize(l->w, l->h); 
    if (img.SetBitDepth(1) == false) 
    { 
    std::cout << "Failed to change Depth" << std::endl; 
    return (1); 
    } 
    std::cout << "Filling Image ..." << std::endl; 
    std::cout << l->w << " " << l->h << std::endl; 
    for (int i = 0; i < l->w; ++i) 
    for (int j = 0; j < l->h; ++j) 
     { 
     if (l->lab[j][i] == WALL) 
     { 
     img(j, i)->Red = 0; 
     img(j, i)->Green = 0; 
     img(j, i)->Blue = 0; 
     img(j, i)->Alpha = 0; 
     } 
     else 
     { 
     img(j, i)->Red = 255; 
     img(j, i)->Green = 255; 
     img(j, i)->Blue = 255; 
     img(j, i)->Alpha = 0; 
     } 
     } 
    std::cout << "Saving Image ..." << std::endl; 
    std::stringstream ss; 
    ss << "Laby-" << MAZE_SIDE << ".bmp"; 
    img.WriteToFile(ss.str().c_str()); 
    return (0); 
} 

Как вы можете видеть, код рисования очень проста, но все же ... Я что-то отсутствует или я пытаюсь сделать что-то я не могу сделать xD?

Заранее благодарим за ваши предложения.

PS: Первоначальная публикация здесь, я старался быть как можно яснее, но рассказываю, если я сделал что-то не так.

Rel4X

+0

Я считаю, что BMP-файлы должны иметь заголовок (http://en.wikipedia.org/wiki/BMP_file_format#File_structure) – braindf

+0

Привет мозг. Да, и кажется, что мои размеры находятся под максимальным размером: заголовок говорит 4 байта по высоте и ширине и общему размеру. 4 байта подписывается примерно как 2000000000 пикселей. У меня 1369000000 пикселей. –

+0

Попробуйте настроить альфа-канал на 255. –

ответ

0

Я много об этой проблеме с помощью easybmp LIB не знаю, но в качестве альтернативы вы можете попробовать использовать Libpng.

Вы можете проверить приведенный ниже код (используя libpng) для записи большего размера файла изображения, также libpng создает много сжатого файла. Вы можете модифицировать код в соответствии с вашими потребностями. Надеюсь, поможет.

/*********************************************************** 
This is a modification of the original code taken from 
http://www.lemoda.net/c/write-png/ 
***********************************************************/ 

#include "png.h" 
#include <stdio.h> 
#include <stdlib.h> 
#include <stdint.h> 

/* A coloured pixel. */ 

typedef struct { 
    char color; 
} pixel_t; 

/* A picture. */ 

typedef struct { 
    pixel_t *pixels; 
    size_t width; 
    size_t height; 
} bitmap_t; 

/* Given "bitmap", this returns the pixel of bitmap at the point 
    ("x", "y"). */ 

static pixel_t * pixel_at (bitmap_t * bitmap, int x, int y) 
{ 
    return bitmap->pixels + bitmap->width * y + x; 
} 

/* Write "bitmap" to a PNG file specified by "path"; returns 0 on 
    success, non-zero on error. */ 

static int save_png_to_file (bitmap_t *bitmap, const char *path) 
{ 
    FILE * fp; 
    png_structp png_ptr = NULL; 
    png_infop info_ptr = NULL; 
    size_t x, y; 
    png_byte ** row_pointers = NULL; 
    png_byte *row = NULL; 
    /* "status" contains the return value of this function. At first 
     it is set to a value which means 'failure'. When the routine 
     has finished its work, it is set to a value which means 
     'success'. */ 
    int status = -1; 
    /* The following number is set by trial and error only. I cannot 
     see where it it is documented in the libpng manual. 
    */ 
    int pixel_size = 1; 
    int depth = 8; 

    fp = fopen (path, "wb"); 
    if (! fp) { 
     goto fopen_failed; 
    } 

    png_ptr = png_create_write_struct (PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); 
    if (png_ptr == NULL) { 
     goto png_create_write_struct_failed; 
    } 

    info_ptr = png_create_info_struct (png_ptr); 
    if (info_ptr == NULL) { 
     goto png_create_info_struct_failed; 
    } 

    /* Set up error handling. */ 

    if (setjmp (png_jmpbuf (png_ptr))) { 
     goto png_failure; 
    } 

    /* Set image attributes. */ 

    png_set_IHDR (png_ptr, 
        info_ptr, 
        bitmap->width, 
        bitmap->height, 
        depth, 
        PNG_COLOR_TYPE_GRAY, 
        PNG_INTERLACE_NONE, 
        PNG_COMPRESSION_TYPE_DEFAULT, 
        PNG_FILTER_TYPE_DEFAULT); 

    /* Initialize rows of PNG. */ 
    printf("Filling image...\n"); 
    png_init_io (png_ptr, fp); 
    png_write_info(png_ptr, info_ptr); 

    row_pointers = png_malloc (png_ptr, sizeof (pixel_t *)); 
    row = png_malloc (png_ptr, sizeof (pixel_t) * bitmap->width * pixel_size); 
    for (y = 0; y < bitmap->height; ++y) { 
     for (x = 0; x < bitmap->width; ++x) { 
      pixel_t * pixel = pixel_at (bitmap, x, y); 
      row[x-1] = pixel->color; 
     } 
     png_write_row(png_ptr, row); 
    } 
    png_free (png_ptr, row_pointers); 

    /* Write the image data to "fp". */ 
    printf("Writing image...\n"); 
    png_write_end(png_ptr, info_ptr); 

    /* The routine has successfully written the file, so we set 
     "status" to a value which indicates success. */ 

    status = 0; 
    /* 
    for (y = 0; y < bitmap->height; y++) { 
     png_free (png_ptr, row_pointers[y]); 
    } 
    png_free (png_ptr, row_pointers); 
    */ 
png_failure: 
png_create_info_struct_failed: 
    png_destroy_write_struct (&png_ptr, &info_ptr); 
png_create_write_struct_failed: 
    fclose (fp); 
fopen_failed: 
    return status; 
} 

/* Given "value" and "max", the maximum value which we expect "value" 
    to take, this returns an integer between 0 and 255 proportional to 
    "value" divided by "max". */ 

static int pix (int value, int max) 
{ 
    if (value < 0) 
     return 0; 
    return (int) (256.0 *((double) (value)/(double) max)); 
} 

int main() 
{ 
    bitmap_t fruit; 
    int x; 
    int y; 

    /* Create an image. */ 

    fruit.width = 37000; 
    fruit.height = 37000; 

    fruit.pixels = calloc (sizeof (pixel_t), fruit.width * fruit.height); 
    printf("creating image...\n"); 
    for (y = 0; y < fruit.height; y++) { 
     for (x = 0; x < fruit.width; x++) { 
      pixel_t * pixel = pixel_at (& fruit, x, y); 
      if((x+y)%2) 
      { 
       pixel->color = 0; 
      } 
      else 
      { 
       pixel->color = 255; 
      } 
     } 
    } 

    /* Write the image to a file 'fruit.png'. */ 

    save_png_to_file (& fruit, "fruit.png"); 

    return 0; 
} 
+0

Спасибо много, я попробую! ... Все еще застрял в этом, у меня очень плохое время xD // –

Смежные вопросы