Пример #1
0
int screenshot_dump_png()
{
	int i, index, width, height, stride;
	char path[MAX_PATH] = "";

	unsigned char r, g, b, a = 255;

	unsigned char* png;
	size_t pngSize;
	LodePNGState state;

	// Get a free screenshot path
	if ((index = screenshot_get_next_path(path, ".png")) == -1)
		return -1;


	lodepng_state_init(&state);
	state.info_raw.colortype = LCT_PALETTE;

	// Get image size
	width = RCT2_GLOBAL(RCT2_ADDRESS_SCREEN_WIDTH, uint16);
	height = RCT2_GLOBAL(RCT2_ADDRESS_SCREEN_HEIGHT, uint16);
	stride = (width + 3) & 0xFFFFFFFC;

	for (i = 0; i < 246; i++) {
		b = RCT2_ADDRESS(0x01424680, uint8)[i * 4 + 0];
		g = RCT2_ADDRESS(0x01424680, uint8)[i * 4 + 1];
		r = RCT2_ADDRESS(0x01424680, uint8)[i * 4 + 2];

		lodepng_palette_add(&state.info_raw, r, g, b, a);
	}

	rct_drawpixelinfo *dpi = RCT2_ADDRESS(RCT2_ADDRESS_SCREEN_DPI, rct_drawpixelinfo);

	unsigned int error = lodepng_encode(&png, &pngSize, dpi->bits, stride, dpi->height, &state);
	if (!error) lodepng_save_file(png, pngSize, path);

	if (error) fprintf(stderr, "error: %u: %s\n", error, lodepng_error_text(error));

	free(png);
	return index;
}
Пример #2
0
int LodePngCoder::Decode(const char *filePath, unsigned char **outputBuffer,
                         unsigned int *outputWidth,
                         unsigned int *outputHeight)
{
    unsigned int uw = 0, uh = 0;
    unsigned char *buffer = NULL;
    int error = lodepng_decode32_file(&buffer, &uw, &uh, filePath);

    if (outputWidth) *outputWidth = uw;
    if (outputHeight) *outputHeight = uh;
    if (outputBuffer) *outputBuffer = buffer;

    if (error)
    {
        LOG_I("[LodePngCoder] fail to decode, error:%d, %s", error,
              lodepng_error_text(error));
    }

    return error;
}
Пример #3
0
//******************
//	Main methods
//******************
MapObject PngUtil::mapObjectFromPng(const char* filename) {
	std::vector<unsigned char> rawImage; // Raw pixels & alpha's
	unsigned width,height;
	unsigned error = lodepng::decode(rawImage,width,height,filename);

	if (error) {
		std::cout << "decoder error " << error << ": "
						<< lodepng_error_text(error) << std::endl;
		throw "PNG decoding error ! " + error;
	}

	MapObject mapObject;
	mapObject.defineDimensions(width, height);

	// Convert the raw pixels to actual grid cells
	convertByteVectorToMapObject(rawImage,mapObject,width,height);

	// Return the loaded map as grid of cells
	return mapObject;
}
Пример #4
0
void binarize(char* input_filename, char* output_filename, int thread_count) {
  unsigned error;
  unsigned char *image;
  unsigned width, height;

  // load image from PNG into C array
  error = lodepng_decode32_file(&image, &width, &height, input_filename);
  if(error) printf("error %u: %s\n", error, lodepng_error_text(error));
  new_image = malloc(width * height * 4 * sizeof(unsigned char));

  struct timeval start, end; // struct used to compute execution time
  gettimeofday(&start, NULL);  // set starting point

  portion = (width * height) / thread_count; //divide up image


  int threads[thread_count];
  int thread;
  for (thread = 0; thread < thread_count; thread++) {
    pthread_t work_thread;
    int *arg = malloc(sizeof(*arg));
    *arg = portion * thread;
    threads[thread] = pthread_create(&work_thread, NULL, worker_thread, arg);
  }
  
  /* TODO: create your thread team here and send each thread an argument 
  telling it which part of "image" to process 

  remember to join all threads!
  */

  gettimeofday(&end, NULL);
  printf("\n\nAlgorithm's computational part duration : %ld\n", \
               ((end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec)));


  lodepng_encode32_file(output_filename, new_image, width, height);

  free(image);
  free(new_image);
}
Пример #5
0
void create_background_texture(background_t *state)
{
    // Read in background PNG
    unsigned error;
    unsigned char* image;
    unsigned width, height;

    #ifdef RASPI
    error = lodepng_decode32_file(&image, &width, &height, "SPH/images/OakRidgeLeaf.png");
    #else
    error = lodepng_decode32_file(&image, &width, &height, "images/OakRidgeLeaf.png");
    #endif
    if(error) printf("error %u: %s\n", error, lodepng_error_text(error));

    state->background_width = state->screen_width/3.2;
    state->background_height = state->screen_height/1.5;

    printf("Background image loaded: %d x %d pixels\n", width, height);

    // Generate texture
    glGenTextures(1, &state->tex_uniform);

    // Set texture unit 0 and bind texture
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, state->tex_uniform);

    // Buffer texture
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image);

    // Set texture parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    // Create Mipmap
    glGenerateMipmap(GL_TEXTURE_2D);

    // Release image host memory
    free(image);
}
Пример #6
0
int LodePngCoder::Decode(const unsigned char *inBuffer,
                         unsigned int bufferLen, unsigned char **outputBuffer,
                         unsigned int *output_width,
                         unsigned int *output_height)
{
    unsigned int uw = 0, uh = 0;
    unsigned char *buffer = NULL;
    int error = lodepng_decode32(&buffer, &uw, &uh, inBuffer, bufferLen);

    if (output_width) *output_width = uw;
    if (output_height) *output_height = uh;
    if (outputBuffer) *outputBuffer = buffer;

    if (error)
    {
        LOG_I("[LodePngCoder] fail to decode, error:%d, %s", error,
              lodepng_error_text(error));
    }

    return error;
}
Пример #7
0
int main(int argv, char **argc) {
    std::vector<std::string> files;

    for (int i = 1; i < argv; i++) {
      files.push_back(argc[i]);
    }

    auto result = process(files);

    auto& image = result.first;

    unsigned error = lodepng::encode("pixelPacker.png", image.pixels, image.width, image.height);

    if (error) {
        std::cout << "encoder error " << error << ": "<< lodepng_error_text(error) << std::endl;
    }

    std::ofstream outputJson("pixelPacker.json");

    outputJson << result.second;
}
Пример #8
0
void so_img_loader_lodepng_load(const char* file, so_img_loader_data_t* info)
{
    unsigned error;
    unsigned char* image;
    unsigned width, height;
    unsigned char* png;
    size_t pngsize;
    char   abs_file_path[FILENAME_MAX];

    ks_helper_path_join_relative_app(abs_file_path, sizeof(abs_file_path), file);

    lodepng_load_file(&png, &pngsize, abs_file_path);
    error = lodepng_decode32(&image, &width, &height, png, pngsize);
    if(error) printf("error %u: %s\n", error, lodepng_error_text(error));

    free(png);

    info->pixels = (char*)image;
    info->width = width;
    info->height = height;
}
Пример #9
0
int imageIO::savePNG(const char* filename, std::vector<unsigned char> &imageBuffer)
{

	std::vector<unsigned char> rawPixels;
	//encode and save
	unsigned int error = 0;

	error = lodepng::encode(rawPixels, imageBuffer, imageWidth, imageHeight);

	if (error)
	{
		std::cout << "Encoding error: " << lodepng_error_text(error) << std::endl;
	}
	else {
		printf("%s", "Saved to ");
		printf("%s \n", filename);
	}

	lodepng::save_file(rawPixels, filename);
	return 0;
}
Пример #10
0
		bool Pixmap::load(const char* chrFilePath)
		{
			DAnsiStr strExt = PS::FILESTRINGUTILS::ExtractFileExt(DAnsiStr(chrFilePath));
			if(strExt.toUpper() == "PNG") {
				std::vector<U8> image;
				U32 width, height;

				//decode
				U32 error = lodepng::decode(image, width, height, chrFilePath);
				if(error) {
					printf("decoder error %d : %s", error, lodepng_error_text(error));
					return false;
				}
				else {
					reset(width, height);
					memcpy(m_bitmap, &image[0], m_width * m_height * 4);
					return true;
				}
			}
			return false;
		}
Пример #11
0
	GLuint loadTexture(const std::string &filename)
	{
		GLuint textureID = 0;
		std::vector<unsigned char> buffer;
		unsigned int width, height;
		unsigned int error = lodepng::decode(buffer, width, height, getAssetDir() + filename);
		if(error)
		{
			std::cout << "ERROR: could not load " << filename << ": " << lodepng_error_text(error) << std::endl;
			ready = false;
			return textureID;
		}

		glGenTextures(1, &textureID);
		glBindTexture(GL_TEXTURE_2D, textureID);
		glTexImage2D(GL_TEXTURE_2D, 0, 4, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, &(buffer[0]));
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

		return textureID;
	}
Пример #12
0
int imageIO::loadPNG(const char* filename, std::vector<unsigned char> &imageBuffer)
{
	std::vector<unsigned char> rawPixels;
	std::string tmp = filename;
	//load and decode
	unsigned int error = 0;
	lodepng::load_file(rawPixels, filename);
	error = lodepng::decode(imageBuffer, imageWidth, imageHeight, rawPixels);

	if (error)
	{
		std::cout << "Error: " << lodepng_error_text(error) << std::endl;
	}
	else {
		printf("%s \n", "File Read Successful");
	}

	imageBytes = 4;
	size = imageWidth * imageHeight * imageBytes;
	return 0;
}
Пример #13
0
void Image::load(const char* mapFilePath) {
	std::vector<unsigned char> rawPixels;

	//decode
	unsigned error = lodepng::decode(rawPixels, width, height, "/home/user/robotics/PcBotWorld/roboticLabMap.png");

	//if there's an error, display it
	if (error)
		std::cout << "decoder error " << error << ": "
				<< lodepng_error_text(error) << std::endl;

	pixels.resize(width * height);

	for (unsigned y = 0; y < height; ++y) {
		for (unsigned x = 0; x < width; ++x) {
			unsigned pos = y*width*4 + x*4;
			Color color(rawPixels[pos], rawPixels[pos + 1], rawPixels[pos + 2], rawPixels[pos + 3]);
			setPixel(x, y, color);
		}
	}
}
Пример #14
0
		bool loadImage(string filename, vector<unsigned char> &m_image, size_t &u2, size_t &v2, double &u3, 
			double &v3, unsigned &width, unsigned &height){

			// Load file and decode image.
			vector<unsigned char> image;
			unsigned error = lodepng::decode(image, width, height, filename);
			// If there's an error, display it.
			if (error != 0)
			{
				std::cout << "error " << error << ": " << lodepng_error_text(error) << std::endl;
				return false;
			}

			// Make some OpenGL properties better for 2D and enable alpha channel.
			glDisable(GL_CULL_FACE);
			glDisable(GL_DEPTH_TEST);
			glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
			glEnable(GL_BLEND);
			glDisable(GL_ALPHA_TEST);

			// Texture size must be power of two for the primitive OpenGL version this is written for. Find next power of two.
			u2 = 1;  while (u2 < width) u2 *= 2;
			v2 = 1;  while (v2 < height) v2 *= 2;
			// Ratio for power of two version compared to actual version, to render the non power of two image with proper size.
			u3 = (double)width / u2;
			v3 = (double)height / v2;

			// Make power of two version of the image.
			std::vector<unsigned char> image2(u2 * v2 * 4);
			for (size_t y = 0; y < height; y++)
				for (size_t x = 0; x < width; x++)
					for (size_t c = 0; c < 4; c++)
					{
						image2[4 * u2 * y + 4 * x + c] = image[4 * width * y + 4 * x + c];
					}

			m_image = image2;

			return true;
		}
void binarize(char* input_filename, char* output_filename, int thread_count)
{
    unsigned error;
    unsigned char *image, *new_image;
    unsigned width, height;

    error = lodepng_decode32_file(&image, &width, &height, input_filename);
    if(error) printf("error %u: %s\n", error, lodepng_error_text(error));
    new_image = malloc(width * height * 4 * sizeof(unsigned char));

    struct timeval start, end; // struct used to compute execution time
    gettimeofday(&start, NULL);  // set starting point

    omp_set_num_threads(thread_count);
    int i, j;
    unsigned char value;
    #pragma omp parallel for shared(new_image) private(i,j,value)
    for (i = 0; i < height; i++) {
        for (j = 0; j < width; j++) {
            if (image[4*width*i + 4*j] > THRESHOLD) {
                value = 255;
            } else {
                value = 0;
            }

            new_image[4*width*i + 4*j] = value;
            new_image[4*width*i + 4*j + 1] = value;
            new_image[4*width*i + 4*j + 2] = value;
            new_image[4*width*i + 4*j + 3] = 255;
        }
    }

    gettimeofday(&end, NULL);
    printf("\n\nAlgorithm's computational part duration : %ld\n", \
           ((end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec)));

    lodepng_encode32_file(output_filename, new_image, width, height);

    free(image);
}
Пример #16
0
// Charge une texture depuis un fichier
void Textures::loadTexture(std::string filename)
{
    unsigned width, height;
    std::vector<unsigned char>image;
    
    unsigned error = lodepng::decode(image, width, height, filename);
    
    if(error) {
        printf("PNG decoding error : %u : %s", error, lodepng_error_text(error));
    }
    
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    //glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE );
    
    gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA,
                      width, height,
                      GL_RGBA, GL_UNSIGNED_BYTE, &image[0]);
}
Пример #17
0
//function for decoding a PNG
Image *decode(const char *filename)
{
  Image *inputImage=(Image*)malloc(sizeof(Image));
  unsigned int error;
  unsigned char *image;

  error=lodepng_decode32_file(&image,(unsigned int*)&(inputImage->width),(unsigned int*)&(inputImage->height),filename);
  if(error)
    printf("error %u: %s\n",error,lodepng_error_text(error));

  int width=inputImage->width;
  int height=inputImage->height;
  inputImage->redChannel=(uint8_t*)malloc(sizeof(uint8_t)*width*height);
  inputImage->blueChannel=(uint8_t*)malloc(sizeof(uint8_t)*width*height);
  inputImage->greenChannel=(uint8_t*)malloc(sizeof(uint8_t)*width*height);
  inputImage->alphaChannel=(uint8_t*)malloc(sizeof(uint8_t)*width*height);

  int row,col;
  int imageWidth=width*4;
  uint8_t *redChannel=inputImage->redChannel;
  uint8_t *blueChannel=inputImage->blueChannel;
  uint8_t *greenChannel=inputImage->greenChannel;
  uint8_t *alphaChannel=inputImage->alphaChannel;

  for(row=0;row<height;row++)
  {
    for(col=0;col<width;col++)
    {
      redChannel[row*width+col]=image[imageWidth*row+4*col+0];
      blueChannel[row*width+col]=image[imageWidth*row+4*col+1];
      greenChannel[row*width+col]=image[imageWidth*row+4*col+2];
      alphaChannel[row*width+col]=image[imageWidth*row+4*col+3];
    }
  }

  free(image);
  return inputImage;
}
Пример #18
0
void Planet::initTexture(int count, const char **filenames)
{
    textureCount = count;
    glEnable(GL_TEXTURE_2D);
    glGenTextures(count, texId);
    
    for (unsigned i = 0; i < textureCount; ++i) {
        std::vector<unsigned char> image;
        unsigned width, height;
        unsigned error = lodepng::decode(image, width, height, filenames[i], LCT_RGB);

        if (error) {
            std::cerr << "Something has gone wrong while trying to load " << filenames[i] << " texture" << std::endl;
            std::cerr << lodepng_error_text(error) << std::endl;
            exit(1);
        }
 
        //make texId current 
        glBindTexture(GL_TEXTURE_2D, texId[i]);
    
        //don't use alignment
        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

        //build mipmaps
        gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, width, height, GL_RGB, GL_UNSIGNED_BYTE, &image[0]);
    
        // Set nearest filtering mode for texture minification
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

        //set Texture Data
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, &image[0]);
    }
    currTexture = 0;
}
/*
Example 3
Load PNG file from disk using a State, normally needed for more advanced usage.
*/
void decodeWithState(const char *filename)
{
    unsigned error;
    unsigned char *image;
    unsigned width, height;
    unsigned char *png;
    size_t pngsize;
    LodePNGState state;

    lodepng_state_init(&state);
    /*optionally customize the state*/

    lodepng_load_file(&png, &pngsize, filename);
    error = lodepng_decode(&image, &width, &height, &state, png, pngsize);
    if (error) printf("error %u: %s\n", error, lodepng_error_text(error));

    free(png);

    /*use image here*/
    /*state contains extra information about the PNG such as text chunks, ...*/

    lodepng_state_cleanup(&state);
    free(image);
}
Пример #20
0
int main(int argc, char *argv[]){
  error= lodepng_decode32_file(&image, &width, &height, "../gfx/numbers4map.png");
  if( error )
    printf("Error %u: %s\n", error, lodepng_error_text(error)),
    exit(-1);
  if( width!= 50 && height!= 21 )
    printf("Error. Bad dimmensions");
  fo= fopen("numbers4map.h", "wb+");
  fprintf(fo, "short n4m[]={");
  if( !fo )
    printf("\nCannot create output file: numbers4map.h\n"),
    exit(-1);
  for ( i= 0; i < 3; i++ )
    for ( j= 0; j < 10; j++ ){
      (i || j) && fprintf(fo, "0x%04x,", m);
      for ( m= k= 0; k < 5; k++ )
        for ( l= 0; l < 3; l++ )
          m<<= 1,
          m|= !image[((7*i+k+1)*50+j*5+l+1)*4];
    }
  fprintf(fo, "0x%04x};", m);
  fclose(fo);
  free(image);
}
Пример #21
0
GLuint LoadTextureFromPNG(const char * filename, unsigned alpha) {
    std::vector<unsigned char> png;
    std::vector<unsigned char> image; 
    lodepng::State state; //optionally customize this one
    unsigned int w, h;

    lodepng::load_file(png, filename); 
    
    unsigned error = lodepng::decode(image,  w,  h, state, png); // decode file into image
    if(error) std::cout << "decoder error " << error << ": "<< lodepng_error_text(error) << std::endl;
    
    //alpha
    if (alpha < 255) {
        for(unsigned y = 0; y < h; y++) {
            for(unsigned x = 0; x < w; x++) {
                image[4 * w * y + 4 * x + 3] *= alpha/255.0;
            }
        }
    }

    //void * ptr = &image[0];
    return AddTextureToOpenGL(w, h, &image[0]);

}
  ColorImageR8G8B8A8 LodePNG::load(const std::string &filename)
  {
    if (!ml::util::fileExists(filename))
    {
      std::cout << ("LodePNG::load file not found: " + filename);
      return ColorImageR8G8B8A8();
    }
    std::vector<BYTE> image;
    UINT width, height;

    UINT error = lodepng::decode(image, width, height, filename);

    MLIB_ASSERT_STR(!error, std::string(lodepng_error_text(error)) + ": " + filename);

    ColorImageR8G8B8A8 result;

    if (!error)
    {
        result.allocate(width, height);
        memcpy(result.getPointer(), &image[0], 4 * width * height);
    }

    return result;
  }
Пример #23
0
Image_t loadPNG(const std::string &filename)
{
    std::cout << "Loading image from " << filename << " ..." << std::endl;  

    std::vector<unsigned char> data;
    unsigned width, height;
    unsigned error = lodepng::decode(data, width, height, filename);
    if (error != 0) {
        std::cout << "Error: " << lodepng_error_text(error) << std::endl;
        std::exit(EXIT_FAILURE);
    }
  
    Image_t image;
    image.width = width;
    image.height = height;
    image.data = data;
  
    std::cout << "Done!" << std::endl;
    std::cout << "Image width: " << image.width << std::endl;
    std::cout << "Image height: " << image.height << std::endl;
    std::cout << "Number of elements: " << image.data.size() << std::endl;
  
    return image;
}
Пример #24
0
static rt_bool_t rtgui_image_png_load(struct rtgui_image *image, struct rtgui_filerw *file, rt_bool_t load)
{
    unsigned int width;
    unsigned int height;
    unsigned int error;
	
    rt_uint8_t* pixel;
    rt_uint8_t* in;
    rt_uint32_t in_size;

    RT_ASSERT(image != RT_NULL);
    RT_ASSERT(file != RT_NULL);

    rtgui_filerw_seek(file, 0, SEEK_END);
    in_size = rtgui_filerw_tell(file);
    in = rtgui_malloc(in_size);
    if (in == RT_NULL) return RT_FALSE; /* out of memory */

    rtgui_filerw_seek(file, 0, SEEK_SET);
    rtgui_filerw_read(file, in, in_size, 1);

    error = lodepng_decode32(&pixel, &width, &height, in, in_size);    
    if(error) 
	{
		rt_kprintf("error %u: %s\n", error, lodepng_error_text(error));
		rtgui_free(in);
		return RT_FALSE;
	}

    rtgui_free(in);

    /* set image information */
    image->w = width;
    image->h = height;
    image->engine = &rtgui_image_png_engine;
    image->data = pixel;

	/* NOTE: the pixel format of PNG is ABGR888, bit0 R,G,B,A bit31 */
	/* convert pixel to ARGB888, swap B/G */
	{
		rt_uint8_t* pixel_ptr;
		rt_uint8_t* pixel_end;

		pixel_ptr = (rt_uint8_t*) pixel;
		pixel_end = pixel_ptr + width * height * 4;

		while (pixel_ptr < pixel_end)
		{
			pixel_ptr[0] = pixel_ptr[0] ^ pixel_ptr[2];
			pixel_ptr[2] = pixel_ptr[0] ^ pixel_ptr[2];
			pixel_ptr[0] = pixel_ptr[0] ^ pixel_ptr[2];

			pixel_ptr += 4;
		}
	}

    /* close file handler */
    rtgui_filerw_close(file);

    return RT_TRUE;
}
Пример #25
0
/*
Show the filtertypes of each scanline in this PNG image.
*/
void displayFilterTypes(const std::vector<unsigned char>& buffer, bool ignore_checksums)
{
  //Get color type and interlace type
  lodepng::State state;
  if(ignore_checksums)
  {
    state.decoder.ignore_crc = 1;
    state.decoder.zlibsettings.ignore_adler32 = 1;
  }
  unsigned w, h;
  unsigned error;
  error = lodepng_inspect(&w, &h, &state, &buffer[0], buffer.size());

  if(error)
  {
    std::cout << "inspect error " << error << ": " << lodepng_error_text(error) << std::endl;
    return;
  }

  if(state.info_png.interlace_method == 1)
  {
    std::cout << "showing filtertypes for interlaced PNG not supported by this example" << std::endl;
    return;
  }

  //Read literal data from all IDAT chunks
  const unsigned char *chunk, *begin, *end, *next;
  end = &buffer.back() + 1;
  begin = chunk = &buffer.front() + 8;

  std::vector<unsigned char> zdata;

  while(chunk + 8 < end && chunk >= begin)
  {
    char type[5];
    lodepng_chunk_type(type, chunk);
    if(std::string(type).size() != 4)
    {
      std::cout << "this is probably not a PNG" << std::endl;
      return;
    }

    if(std::string(type) == "IDAT")
    {
      const unsigned char* cdata = lodepng_chunk_data_const(chunk);
      unsigned clength = lodepng_chunk_length(chunk);
      if(chunk + clength + 12 > end || clength > buffer.size() || chunk + clength + 12 < begin) {
        std::cout << "invalid chunk length" << std::endl;
        return;
      }

      for(unsigned i = 0; i < clength; i++)
      {
        zdata.push_back(cdata[i]);
      }
    }

    next = lodepng_chunk_next_const(chunk);
    if (next <= chunk) break; // integer overflow
    chunk = next;
  }

  //Decompress all IDAT data
  std::vector<unsigned char> data;
  error = lodepng::decompress(data, &zdata[0], zdata.size());

  if(error)
  {
    std::cout << "decompress error " << error << ": " << lodepng_error_text(error) << std::endl;
    return;
  }

  //A line is 1 filter byte + all pixels
  size_t linebytes = 1 + lodepng_get_raw_size(w, 1, &state.info_png.color);

  if(linebytes == 0)
  {
    std::cout << "error: linebytes is 0" << std::endl;
    return;
  }

  std::cout << "Filter types: ";
  for(size_t i = 0; i < data.size(); i += linebytes)
  {
    std::cout << (int)(data[i]) << " ";
  }
  std::cout << std::endl;

}
Пример #26
0
IPXdevLFont XdevLFontSystemRAI::createFromFontFile(IPXdevLFile& file) {
    assert(m_rai && " XdevLFontImpl::createFromFontFile: XdevLFontSystem not initialized.");

    std::vector<std::string> fileNames;
    xdl_int numberOfTextures = 1;
    xdl_uint fontSize = 0;

    XdevLString tmp;
    file->readString(tmp);
    file->readString(tmp);

    // Get font size.
    file->readString(tmp);
    std::stringstream ss(tmp.toString());
    ss >> fontSize;

    // Create the font instance.
    auto font = new XdevLFontRAI();
    font->setFontSize(fontSize);

    // Reset stringstream.
    ss.str("");
    ss.clear();

    file->readString(tmp);
    ss << tmp;
    ss >> numberOfTextures;


    IPXdevLTexture texture = nullptr;

    auto archive = file->getArchive();

    for(auto id = 0; id < numberOfTextures; id++) {
        XdevLFileName filename;
        file->readString(filename);

        // Did the user specify a external functions to create a texture out of an image file?
        if(createTextureFromFile) {
            auto file = archive->open(XdevLOpenForReadOnly(), XdevLFileName(filename));
            // Yes, they use that to create the texture.
            texture = createTextureFromFile(file.get());

        } else {
            // No, let's use the lodepng project import PNG files.
            std::vector<xdl_uint8> imageIn, imageOut;
            auto newFile = archive->open(XdevLOpenForReadOnly(), filename);

            imageIn.reserve(newFile->length());
            imageIn.resize(newFile->length());

            newFile->read(imageIn.data(), newFile->length());
            newFile->close();

            xdl_uint width, height;

            xdl_int error = lodepng::decode(imageOut, width, height, imageIn);
            if(error) {
                std::cout << "decoder error " << error << ": " << lodepng_error_text(error) << std::endl;
                return std::shared_ptr<XdevLFontRAI>();
            }

            // This flipping is neccessary because the library flips the picture up side down.
            // Method is brute force and needs unessarly memory. It creates a vector the same size
            // and starts copying which is not effective at all.
            std::vector<xdl_uint8> vflipedimage(imageOut);
            for(xdl_uint y = 0; y != height; y++) {
                for(xdl_uint x = 0; x != width*4; x++) {
                    vflipedimage[x + y*width*4] = imageOut[x + (height - 1 - y)*width*4];
                }
            }

            texture = m_rai->createTexture();

            texture->init(width, height, XDEVL_RGBA, XDEVL_RGBA, vflipedimage.data());
            imageOut.clear();
            vflipedimage.clear();

        }
        if(texture == nullptr) {
            XDEVL_MODULEX_ERROR(XdevLFontSystemRAI, "XdevLFontImpl::importFromFontFile: Could not create texture: " << filename << std::endl);
            assert(texture && "FontTexture not created.");
        }

        // Setup the texture.
        texture->lock();
        texture->setTextureFilter(XDEVL_TEXTURE_MIN_FILTER, XDEVL_NEAREST);
        texture->setTextureFilter(XDEVL_TEXTURE_MAG_FILTER, XDEVL_NEAREST);
        texture->setTextureWrap(XDEVL_TEXTURE_WRAP_S, XDEVL_CLAMP_TO_EDGE);
        texture->setTextureWrap(XDEVL_TEXTURE_WRAP_T, XDEVL_CLAMP_TO_EDGE);
        texture->unlock();

        font->addFontTexture(texture);

    }

    calculateGlyphInformation(font, file);

    return std::shared_ptr<XdevLFontRAI>(font);
}
Пример #27
0
int main() {
    //    int width = 256, height = 256;
    int width = 256, height = 256;    
    size_t image_size = width * height * 4;
    unsigned char *image = (unsigned char*) malloc( width * height * 4 ); // PNG用の画像
    // JPEG用の画像
    JSAMPARRAY jsimg = (JSAMPARRAY) malloc( sizeof(JSAMPROW) * height );
    for(int y=0;y<height;y++) {
        jsimg[y] = (JSAMPROW) malloc( sizeof(JSAMPLE)*3*width);
    }
    
    size_t snpsize = image_size * 2;
    char *snappied = (char*) malloc( snpsize);
    for(int i=0;i<100;i++) {
        double t0 = now();
        
        for(int i=0;i<width*height;i++) {
            int x = i % width;
            int y = height - 1 - (i/width);
            int ii = y * width + x;
            // rgbaにならべるが、メモリは、 abgrにならんでいるのと、上下逆
            image[ii*4+3] = 0xff; // alpha
#if 0
            // これでやるとsnappyとlz4は、最悪ケースになるようだ。。
            image[ii*4+0] = x%0xff; // r
            image[ii*4+1] = y%0xff; // g 
            image[ii*4+2] = (x+y)%0xff; // b
#else

            image[ii*4+0] = x%0xff;
            image[ii*4+1] = (y/16)*15;
            image[ii*4+2] = (x/16)*15;
#endif

            // JPEG用
            jsimg[y][x*3+0] = x%0xff; 
            jsimg[y][x*3+1] = y%0xff;
            jsimg[y][x*3+2] = (x+y)%0xff;
        }

        double t1 = now();
        // LodePNG        
        std::vector<unsigned char> png;    
        unsigned e = lodepng::encode( png, image, width, height );
        if(e) {
            print("lodepng::encode error:%s", lodepng_error_text(e) );
            return false;
        }
        double t2 = now();

        unsigned char *ptr = & png[0];
        FILE *fp = fopen( "hoge.png", "w");
        size_t writesz = fwrite( ptr, 1, png.size(), fp );
        fclose(fp);

        double t3 = now();
        // Snappy
        int sr = memCompressSnappy( snappied, snpsize, (char*) image, image_size );

        double t4 = now();
        // LZ4
        int lr = memCompressLZ4( snappied, snpsize, (const char*)image, image_size );
        double t5 = now();

        // libjpeg


        struct jpeg_compress_struct cinfo;
        struct jpeg_error_mgr jerr;
        cinfo.err = jpeg_std_error(&jerr);
        jpeg_create_compress( &cinfo);
        FILE *jfp = fopen( "hoge.jpg", "w");
        jpeg_stdio_dest(&cinfo,jfp);
        cinfo.image_width = width;
        cinfo.image_height = height;
        cinfo.input_components = 3;
        cinfo.in_color_space = JCS_RGB;
        jpeg_set_defaults( &cinfo);
        jpeg_set_quality( &cinfo, 75, true );
        jpeg_start_compress( &cinfo, true );
        jpeg_write_scanlines( &cinfo, jsimg, height );
        jpeg_finish_compress( &cinfo );
        fclose(jfp);
        double t6 = now();
        
        print("img:%f png:%f pngsz:%d snp:%f snpsz:%d lz4:%f lz4sz:%d jpeg:%f",t1-t0,t2-t1, writesz, t4-t3, sr, t5-t4, lr, t6-t5 );
        
        
    }
    return 0;
}
Пример #28
0
bool sprite_file_import(const char *path, rct_g1_element *outElement, uint8 **outBuffer, int *outBufferLength, int mode)
{
	unsigned char *pixels;
	unsigned int width, height;
	unsigned int pngError;

	memcpy(spriteFilePalette, _standardPalette, 256 * 4);

	pngError = lodepng_decode_file(&pixels, &width, &height, path, LCT_RGBA, 8);
	if (pngError != 0) {
		fprintf(stderr, "Error creating PNG data, %u: %s", pngError, lodepng_error_text(pngError));
		return false;
	}

	if (width > 256 || height > 256) {
		fprintf(stderr, "Only images 256x256 or less are supported.");
		free(pixels);
		return false;
	}

	uint8 *buffer = malloc((height * 2) + (width * height * 16));
	uint16 *yOffsets = (uint16*)buffer;

	// A larger range is needed for proper dithering
	sint16 *src = malloc(height * width * 4 * 2);
	for (uint32 x = 0; x < height * width * 4; x++){
		src[x] = (sint16) pixels[x];
	}

	uint8 *dst = buffer + (height * 2);
	
	for (unsigned int y = 0; y < height; y++) {
		rle_code *previousCode, *currentCode;

		yOffsets[y] = (dst - buffer);

		previousCode = NULL;
		currentCode = (rle_code*)dst;
		dst += 2;
		int startX = 0;
		int pixels = 0;
		bool pushRun = false;
		for (unsigned int x = 0; x < width; x++) {
			int paletteIndex = get_palette_index(src);

			if (mode == MODE_CLOSEST || mode == MODE_DITHERING)
				if (paletteIndex == -1 && !is_transparent_pixel(src))
					paletteIndex = get_closest_palette_index(src);
			

			if (mode == MODE_DITHERING)
				if (!is_transparent_pixel(src) && is_changable_pixel(get_palette_index(src))){
					sint16 dr = src[0] - (sint16)(spriteFilePalette[paletteIndex].r);
					sint16 dg = src[1] - (sint16)(spriteFilePalette[paletteIndex].g);
					sint16 db = src[2] - (sint16)(spriteFilePalette[paletteIndex].b);

					if (x + 1 < width){
						if (!is_transparent_pixel(src + 4) && is_changable_pixel(get_palette_index(src + 4))){
							// Right
							src[4] += dr * 7 / 16;
							src[5] += dg * 7 / 16;
							src[6] += db * 7 / 16;
						}
					}

					if (y + 1 < height){
						if (x > 0){
							if (!is_transparent_pixel(src + 4 * (width - 1)) && is_changable_pixel(get_palette_index(src + 4 * (width - 1)))){
								// Bottom left
								src[4 * (width - 1)] += dr * 3 / 16;
								src[4 * (width - 1) + 1] += dg * 3 / 16;
								src[4 * (width - 1) + 2] += db * 3 / 16;
							}
						}

						// Bottom
						if (!is_transparent_pixel(src + 4 * width) && is_changable_pixel(get_palette_index(src + 4 * width))){
							src[4 * width] += dr * 5 / 16;
							src[4 * width + 1] += dg * 5 / 16;
							src[4 * width + 2] += db * 5 / 16;
						}

						if (x + 1 < width){
							if (!is_transparent_pixel(src + 4 * (width - 1)) && is_changable_pixel(get_palette_index(src + 4 * (width + 1)))){
								// Bottom right
								src[4 * (width + 1)] += dr * 1 / 16;
								src[4 * (width + 1) + 1] += dg * 1 / 16;
								src[4 * (width + 1) + 2] += db * 1 / 16;
							}
						}
					}
				}

			src += 4;
			if (paletteIndex == -1) {
				if (pixels != 0) {
					x--;
					src -= 4;
					pushRun = true;
				}
			} else {
				if (pixels == 0)
					startX = x;
				pixels++;
				*dst++ = (uint8)paletteIndex;
			}
			if (pixels == 127 || x == width - 1)
				pushRun = true;

			if (pushRun) {
				if (pixels > 0) {
					previousCode = currentCode;
					currentCode->num_pixels = pixels;
					currentCode->offset_x = startX;

					if (x == width - 1)
						currentCode->num_pixels |= 0x80;

					currentCode = (rle_code*)dst;
					dst += 2;
				} else {
					if (previousCode == NULL) {
						currentCode->num_pixels = 0x80;
						currentCode->offset_x = 0;
					} else {
						previousCode->num_pixels |= 0x80;
						dst -= 2;
					}
				}
				startX = 0;
				pixels = 0;
				pushRun = false;
			}
		}
	}
	free(pixels);

	int bufferLength = (int)(dst - buffer);
	buffer = realloc(buffer, bufferLength);

	outElement->offset = buffer;
	outElement->width = width;
	outElement->height = height;
	outElement->flags = G1_FLAG_RLE_COMPRESSION;
	outElement->x_offset = 0;
	outElement->y_offset = 0;
	outElement->zoomed_offset = 0;

	*outBuffer = buffer;
	*outBufferLength = bufferLength;
	return true;
}
Пример #29
0
int main(VOID * task, int argc, char * argv[])
{
  	unsigned w, h, x, y;
	
	if(argc != 2)
	{
		printf("usage: showpng pngFileName");
		return -1;
	}
	char * tmp = NULL;
	if(detect_filename(argv[1], &tmp) == FALSE)
	{
		printf("the file \"%s\" is not exists\n", argv[1]);
		return -1;
	}
	if(tmp == NULL)
		tmp = argv[1];
	printf("now load and decode %s\n", tmp);
	unsigned error = lodepng_decode32_file(&image, &w, &h, tmp);
	/*stop if there is an error*/
	if(error)
	{
		printf("decoder error %u: %s", error, lodepng_error_text(error));
		if(tmp != argv[1])
			free(tmp);
		return 0;
	}
	if(tmp != argv[1])
		free(tmp);

	/*avoid too large window size by downscaling large image*/
	if(w / 1024 >= jump) jump = w / 1024 + 1;
	if(h / 1024 >= jump) jump = h / 1024 + 1;

	img_w = w;
	img_h = h;

	VOID * hshowpng = NULL;
	showpng.x = 310;
	showpng.y = 160;
	showpng.width = w / jump + 2;
	showpng.height = h / jump + 21;
	showpng.mywin_callback = (MY_WINDOW_CALLBACK)showpng_win_callback;
	showpng.task = task;
	hshowpng = (VOID *)syscall_create_my_window(&showpng);
	TASK_MSG msg;
	int ret;
	while(TRUE)
	{
		ret = syscall_get_tskmsg(task,&msg,TRUE);
		if(ret != 1)
		{
			syscall_idle_cpu();
			continue;
		}
		switch(msg.type)
		{
		case MT_CREATE_MY_WINDOW:
			syscall_dispatch_win_msg(&msg, hshowpng);
			break;
		case MT_CLOSE_MY_WINDOW:
			return 0;
			break;
		default:
			break;
		}
	}
	return 0;
}
Пример #30
0
int main(int argc, char** argv){
    if(argc < 3){
        std::cout << "usage:" << argv[0] << " src.png dst.png" << std::endl;
        return 1;
    }
    int mode = 0;  // for cuda
    if(argc == 4){ // this is silly implementation
        char* m = argv[3];
        mode = m[0] - '0';
    }

    const char* input_file  = argv[1];
    const char* output_file = argv[2];
    std::vector<unsigned char> in_image;

    unsigned int width, height;
    const unsigned input_error = lodepng::decode(in_image, width, height, input_file);
    if(input_error){
        std::cout << "decoder error " << input_error << ": " << lodepng_error_text(input_error) << std::endl;
        return 1;
    }

    unsigned char* input_image  = new unsigned char[in_image.size()];
    unsigned char* output_image = new unsigned char[in_image.size()];
    std::copy(in_image.begin(), in_image.end(), input_image);

    // first CUDA call takes a whlie.
    //   For benchmark, I do not take account of first call.
    const int N = 5;
    long sum_of_n_minus_one = 0;
    for(int i=0;i<N;i++){
        struct timeval st;
        struct timeval et;
        gettimeofday(&st, NULL);
        if(mode == 0){
            rgb_invert_in_cuda(output_image, input_image, width, height);
        }else if(mode == 1){
            rgb_invert_in_cpu(output_image, input_image, width, height);
        }else if(mode == 2){
            rgb_invert_in_cuda_uchar_array(output_image, input_image, width, height);
        }else{
            std::cout << "ERROR: unknown mode: " << mode << std::endl;
            return 1;
        }
        gettimeofday(&et, NULL);
        long us = time_diff_us(st, et);
        if(i != 0){
            sum_of_n_minus_one += us;
        }
    }
    printf("%lu\n",sum_of_n_minus_one/(N-1));

    std::vector<unsigned char> out_image(output_image, output_image+in_image.size());
    unsigned output_error = lodepng::encode(output_file, out_image, width, height);
    if(output_error){
        std::cout << "encoder error " << output_error << ": "<< lodepng_error_text(output_error) << std::endl;
        return 1;
    }

    return 0;
}