Beispiel #1
0
int
	SOIL_save_image
	(
		const char *filename,
		int image_type,
		int width, int height, int channels,
		const unsigned char *const data
	)
{
	int save_result;

	/*	error check	*/
	if( (width < 1) || (height < 1) ||
		(channels < 1) || (channels > 4) ||
		(data == NULL) ||
		(filename == NULL) )
	{
		return 0;
	}
	if( image_type == SOIL_SAVE_TYPE_BMP )
	{
		save_result = stbi_write_bmp( filename,
				width, height, channels, (void*)data );
	} else
	if( image_type == SOIL_SAVE_TYPE_TGA )
	{
		save_result = stbi_write_tga( filename,
				width, height, channels, (void*)data );
	} else
	if( image_type == SOIL_SAVE_TYPE_DDS )
	{
		save_result = save_image_as_DDS( filename,
				width, height, channels, (const unsigned char *const)data );
	} else
	{
		save_result = 0;
	}
	if( save_result == 0 )
	{
		result_string_pointer = "Saving the image failed";
	} else
	{
		result_string_pointer = "Image saved";
	}
	return save_result;
}
Beispiel #2
0
int image_ImageData_save(image_ImageData *dst, const char* format, const char* filename) {
	int succeded = 0;
	if (strncmp(format, "png", 3) == 0)
		succeded = stbi_write_png(filename, dst->w, dst->h, dst->c, (const float*)dst->pixels, 0);
	else if (strncmp(format, "bmp", 3) == 0)
     	succeded = stbi_write_bmp(filename, dst->w, dst->h, dst->c, (const float*)dst->surface);
	else if (strncmp(format, "tga", 3) == 0)
     	succeded = stbi_write_tga(filename, dst->w, dst->h, dst->c, (const float*)dst->pixels);
	else if (strncmp(format, "hdr", 3) == 0)
     	succeded = stbi_write_hdr(filename, dst->w, dst->h, dst->c, (const float*)dst->surface);
	else
		printf("%s %s %s \n", "Error, format:", format,  " is not avalabile.Only png,bmp,tga and hdr image formats are possible");
	if(succeded != 0)
		return 1;
	else {
		printf("%s %s \n", "Error: failed to save imageData: ", filename);
		return 0;
	}
}
Beispiel #3
0
void image::saveImageRGB(string filename){
    unsigned char* bitmapData = new unsigned char[3 * xSize * ySize];
    int i = 0;
    
    //read data to buffer for stb_image output
    for(int y = 0; y < ySize; y++) {
        for(int x = 0; x < xSize; x++) { 
            if(gamma.applyGamma){
                bitmapData[i]   = (unsigned char)utilityCore::clamp(applyGamma(readPixelR(x,y))*255,0,255);
                bitmapData[i+1] = (unsigned char)utilityCore::clamp(applyGamma(readPixelG(x,y))*255,0,255);
                bitmapData[i+2] = (unsigned char)utilityCore::clamp(applyGamma(readPixelB(x,y))*255,0,255);
            }else{
                bitmapData[i]   = (unsigned char)utilityCore::clamp(readPixelR(x,y)*255, 0, 255);
                bitmapData[i+1] = (unsigned char)utilityCore::clamp(readPixelG(x,y)*255, 0, 255);
                bitmapData[i+2] = (unsigned char)utilityCore::clamp(readPixelB(x,y)*255, 0, 255);
                
            }
            i=i+3;
        }
    }
    
    //check requested output type
    int imagetype = 0; //0 for png, 1 for bmp
    
    if(filename[filename.size()-1]=='\r'){
        //OSX Version
        if(filename[filename.size()-4]=='b' && filename[filename.size()-3]=='m' && filename[filename.size()-2]=='p'){
            imagetype = 1;
        }
    }else{
        //Windows Version
        if(filename[filename.size()-3]=='b' && filename[filename.size()-2]=='m' && filename[filename.size()-1]=='p'){
            imagetype = 1;
        }
    }
    
    //write output file
    if(imagetype==1){
        stbi_write_bmp(filename.c_str(), xSize, ySize, 3, bitmapData);
    }else{
        stbi_write_png(filename.c_str(), xSize, ySize, 3, bitmapData, xSize * 3);
    }
}
void ImageTargetFileStbImage::finalize()
{
	if( mExtension == "png" ) {
		if( ! stbi_write_png( mFilePath.string().c_str(), (int)mWidth, (int)mHeight, mNumComponents, mData.get(), (int)mRowBytes ) )
			throw ImageIoExceptionFailedWrite();
	}
	else if( mExtension == "bmp" ) {
		if( ! stbi_write_bmp( mFilePath.string().c_str(), (int)mWidth, (int)mHeight, mNumComponents, mData.get() ) )
			throw ImageIoExceptionFailedWrite();
	}
	else if( mExtension == "tga" ) {
		if( ! stbi_write_tga( mFilePath.string().c_str(), (int)mWidth, (int)mHeight, mNumComponents, mData.get() ) )
			throw ImageIoExceptionFailedWrite();
	}
	else if( mExtension == "hdr" ) {
		if( ! stbi_write_hdr( mFilePath.string().c_str(), (int)mWidth, (int)mHeight, mNumComponents, (const float*)mData.get() ) )
			throw ImageIoExceptionFailedWrite();
	}
}
Beispiel #5
0
bool Image::SaveBMP(const String& fileName)
{
    FileSystem* fileSystem = GetSubsystem<FileSystem>();
    if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
    {
        LOGERROR("Access denied to " + fileName);
        return false;
    }
    
    if (IsCompressed())
    {
        LOGERROR("Can not save compressed image to BMP");
        return false;
    }
    
    if (data_)
        return stbi_write_bmp(fileName.CString(), width_, height_, components_, data_.Get()) != 0;
    else
        return false;
}
Beispiel #6
0
bool ImageLoader::saveImageToFile(const std::string& filename, const std::vector<Uint8>& pixels, unsigned int width, unsigned int height)
{
    // Make sure the image is not empty
    if (!pixels.empty() && width && height)
    {
        // Deduce the image type from its extension
        if (filename.size() > 3)
        {
            // Extract the extension
            std::string extension = filename.substr(filename.size() - 3);

            if (toLower(extension) == "bmp")
            {
                // BMP format
                if (stbi_write_bmp(filename.c_str(), width, height, 4, &pixels[0]))
                    return true;
            }
            else if (toLower(extension) == "tga")
            {
                // TGA format
                if (stbi_write_tga(filename.c_str(), width, height, 4, &pixels[0]))
                    return true;
            }
            else if(toLower(extension) == "png")
            {
                // PNG format
                if (stbi_write_png(filename.c_str(), width, height, 4, &pixels[0], 0))
                    return true;
            }
            else if (toLower(extension) == "jpg")
            {
                // JPG format
                if (writeJpg(filename, pixels, width, height))
                    return true;
            }
        }
    }

    err() << "Failed to save image \"" << filename << "\"" << std::endl;
    return false;
}
Beispiel #7
0
void Gosu::saveImageFile(const Gosu::Bitmap& bitmap, const std::wstring& filename)
{
    int ok;
    std::string utf8 = Gosu::wstringToUTF8(filename);
    
    if (isExtension(filename.c_str(), L"bmp"))
    {
        ok = stbi_write_bmp(utf8.c_str(), bitmap.width(), bitmap.height(), 4, bitmap.data());
    }
    else if (isExtension(filename.c_str(), L"tga"))
    {
        ok = stbi_write_tga(utf8.c_str(), bitmap.width(), bitmap.height(), 4, bitmap.data());
    }
    else
    {
        ok = stbi_write_png(utf8.c_str(), bitmap.width(), bitmap.height(), 4, bitmap.data(), 0);
    }
    
    if (ok == 0)
        throw std::runtime_error("Could not save image data to file: " + utf8);
}
Beispiel #8
0
bool ImageLoader::saveImageToFile(const std::string& filename, const std::vector<Uint8>& pixels, const Vector2u& size)
{
    // Make sure the image is not empty
    if (!pixels.empty() && (size.x > 0) && (size.y > 0))
    {
        // Deduce the image type from its extension

        // Extract the extension
        const std::size_t dot = filename.find_last_of('.');
        const std::string extension = dot != std::string::npos ? toLower(filename.substr(dot + 1)) : "";

        if (extension == "bmp")
        {
            // BMP format
            if (stbi_write_bmp(filename.c_str(), size.x, size.y, 4, &pixels[0]))
                return true;
        }
        else if (extension == "tga")
        {
            // TGA format
            if (stbi_write_tga(filename.c_str(), size.x, size.y, 4, &pixels[0]))
                return true;
        }
        else if (extension == "png")
        {
            // PNG format
            if (stbi_write_png(filename.c_str(), size.x, size.y, 4, &pixels[0], 0))
                return true;
        }
        else if (extension == "jpg" || extension == "jpeg")
        {
            // JPG format
            if (writeJpg(filename, pixels, size.x, size.y))
                return true;
        }
    }

    err() << "Failed to save image \"" << filename << "\"" << std::endl;
    return false;
}
Beispiel #9
0
///\todo is there a write error message too?
bool writeImage(const LDRImage& img, const std::string& filename)
{

    if(!img)
    {
        throw std::runtime_error("Image::Write called on incomplete image");
    }

    std::string extension = filename.substr(filename.length()-4, 4);

    int width =img.getDimensions()[1];
    int height=img.getDimensions()[2];
    int channels=img.getDimensions()[0];

    //special case branching... mostly becuase jpeg doens't write with this writer.  This allows autodetection of the extension regardless though.

    if(extension == ".png")
    {

        return stbi_write_png(filename.c_str(), width, height, channels, img.dataPtr(), width*channels);

    }
    else if(extension==".bmp")
    {

        return stbi_write_bmp(filename.c_str(), width, height, channels, img.dataPtr());

    }
    else if(extension == ".tga")
    {

        return stbi_write_tga(filename.c_str(), width, height, channels, img.dataPtr());
    }
    else
    {
        throw std::runtime_error("Unimplemented extension for image writer");
    }

    return false;
}
Beispiel #10
0
void CNormalGenerator::SaveToFile(const tchar *pszFilename)
{
	if (!pszFilename)
		return;

	tstring sFilename = pszFilename;

	tvector<Color> aclrTexels;
	aclrTexels.resize(m_iNormal2Width*m_iNormal2Height);

	for (size_t i = 0; i < aclrTexels.size(); i++)
		aclrTexels[i] = m_avecNormal2Texels[i];

	if (sFilename.endswith(".png"))
		stbi_write_png(sFilename.c_str(), m_iNormal2Width, m_iNormal2Height, 3, aclrTexels.data(), 0);
	else if (sFilename.endswith(".tga"))
		stbi_write_tga(sFilename.c_str(), m_iNormal2Width, m_iNormal2Height, 3, aclrTexels.data());
	else if (sFilename.endswith(".bmp"))
		stbi_write_bmp(sFilename.c_str(), m_iNormal2Width, m_iNormal2Height, 3, aclrTexels.data());
	else
		TUnimplemented();
}
Beispiel #11
0
    void BitmapData::save(const char* path) const
    {
        const char* ext = strrchr(path, '.');
        if (ext == NULL)
        {
            lmLogError(gGFXLogGroup, "No extension in path %s. Unable to detect file format.", path);
            return;
        }

        if (stricmp(ext, ".bmp") == 0)
        {
            if (stbi_write_bmp(path, w, h, DATA_BPP, data) != 1)
            {
                lmLogError(gGFXLogGroup, "Unable to write image %s", path);
            }
            return;
        }

        if (stricmp(ext, ".png") == 0)
        {
            if (stbi_write_png(path, w, h, DATA_BPP, data, w * DATA_BPP) != 1)
            {
                lmLogError(gGFXLogGroup, "Unable to write image %s", path);
            }
            return;
        }

        if (stricmp(ext, ".tga") == 0)
        {
            if (stbi_write_tga(path, w, h, DATA_BPP, data) != 1)
            {
                lmLogError(gGFXLogGroup, "Unable to write image %s", path);
            }
            return;
        }

        lmLogError(gGFXLogGroup, "Unsupported image extension in path %s.", path);
    }
        int write_bmp(char const *filename, int x, int y, int comp, Array<unsigned char> bytes,
        	unsigned int byteOffset, unsigned int byteLength)
	    {
	        return stbi_write_bmp(filename, x, y, comp, &bytes[0] + byteOffset);
	    }
Beispiel #13
0
	bool Image::save(core::FileSystem::Ptr fs, const std::string &filename)
	{
		if (type != TextureType::Texture2D)
			return false;
		unsigned int components = 0;
		if (format == TextureFormat::R8)
			components = 1;
		else if (format == TextureFormat::RG8)
			components = 2;
		else if (format == TextureFormat::RGBA8)
			components = 4;
		if (components == 0)
			return false;
		std::string extension = tolower(filename.substr(filename.rfind(".")));
		if (extension == ".png")
		{
			core::File::Ptr file = fs->open(filename,
			                                core::FileAccess::Write,
			                                true);
			if (!file)
				return false;
			unsigned int stride = TextureFormat::getSize(format, width, 1, 1);
			if (!stbi_write_png(file,
			                    width,
			                    height,
			                    components,
			                    imagedata,
			                    stride))
				return false;
		}
		else if (extension == ".tga")
		{
			core::File::Ptr file = fs->open(filename,
			                                core::FileAccess::Write,
			                                true);
			if (!file)
				return false;
			if (!stbi_write_tga(file,
			                    width,
			                    height,
			                    components,
			                    imagedata))
				return false;
		}
		else if (extension == ".bmp")
		{
			core::File::Ptr file = fs->open(filename,
			                                core::FileAccess::Write,
			                                true);
			if (!file)
				return false;
			if (!stbi_write_bmp(file,
			                    width,
			                    height,
			                    components,
			                    imagedata))
				return false;
		}
		else
		{
			return false;
		}
		return true;
	}
Beispiel #14
0
int main(int argc, char **argv)
{
   int w,h;
   //test_ycbcr();

   #if 0
   // test hdr asserts
   for (h=0; h < 100; h += 2)
      for (w=0; w < 200; ++w)
         hdr_data[h][w][0] = (float) rand(),
         hdr_data[h][w][1] = (float) rand(),
         hdr_data[h][w][2] = (float) rand();

   stbi_write_hdr("output/test.hdr", 200,200,3,hdr_data[0][0]);
   #endif

   if (argc > 1) {
      int i, n;

      for (i=1; i < argc; ++i) {
         int res;
         int w2,h2,n2;
         unsigned char *data;
         printf("%s\n", argv[i]);
         res = stbi_info(argv[1], &w2, &h2, &n2);
         data = stbi_load(argv[i], &w, &h, &n, 4); if (data) free(data); else printf("Failed &n\n");
         data = stbi_load(argv[i], &w, &h,  0, 1); if (data) free(data); else printf("Failed 1\n");
         data = stbi_load(argv[i], &w, &h,  0, 2); if (data) free(data); else printf("Failed 2\n");
         data = stbi_load(argv[i], &w, &h,  0, 3); if (data) free(data); else printf("Failed 3\n");
         data = stbi_load(argv[i], &w, &h, &n, 4);
         assert(data);
         assert(w == w2 && h == h2 && n == n2);
         assert(res);
         if (data) {
            char fname[512];
            stb_splitpath(fname, argv[i], STB_FILE);
            stbi_write_png(stb_sprintf("output/%s.png", fname), w, h, 4, data, w*4);
            stbi_write_bmp(stb_sprintf("output/%s.bmp", fname), w, h, 4, data);
            stbi_write_tga(stb_sprintf("output/%s.tga", fname), w, h, 4, data);
            stbi_write_png_to_func(dummy_write,0, w, h, 4, data, w*4);
            stbi_write_bmp_to_func(dummy_write,0, w, h, 4, data);
            stbi_write_tga_to_func(dummy_write,0, w, h, 4, data);
            free(data);
         } else
            printf("FAILED 4\n");
      }
   } else {
      int i, nope=0;
      #ifdef PNGSUITE_PRIMARY
      char **files = stb_readdir_files("pngsuite/primary");
      #else
      char **files = stb_readdir_files("images");
      #endif
      for (i=0; i < stb_arr_len(files); ++i) {
         int n;
         char **failed = NULL;
         unsigned char *data;
         printf(".");
         //printf("%s\n", files[i]);
         data = stbi_load(files[i], &w, &h, &n, 0); if (data) free(data); else stb_arr_push(failed, "&n");
         data = stbi_load(files[i], &w, &h,  0, 1); if (data) free(data); else stb_arr_push(failed, "1");
         data = stbi_load(files[i], &w, &h,  0, 2); if (data) free(data); else stb_arr_push(failed, "2");
         data = stbi_load(files[i], &w, &h,  0, 3); if (data) free(data); else stb_arr_push(failed, "3");
         data = stbi_load(files[i], &w, &h,  0, 4); if (data)           ; else stb_arr_push(failed, "4");
         if (data) {
            char fname[512];

            #ifdef PNGSUITE_PRIMARY
            int w2,h2;
            unsigned char *data2;
            stb_splitpath(fname, files[i], STB_FILE_EXT);
            data2 = stbi_load(stb_sprintf("pngsuite/primary_check/%s", fname), &w2, &h2, 0, 4);
            if (!data2)
               printf("FAILED: couldn't load 'pngsuite/primary_check/%s\n", fname);
            else {
               if (w != w2 || h != w2 || 0 != memcmp(data, data2, w*h*4)) {
                  int x,y,c;
                  if (w == w2 && h == h2)
                     for (y=0; y < h; ++y)
                        for (x=0; x < w; ++x)
                           for (c=0; c < 4; ++c)
                              assert(data[y*w*4+x*4+c] == data2[y*w*4+x*4+c]);
                  printf("FAILED: %s loaded but didn't match PRIMARY_check 32-bit version\n", files[i]);
               }
               free(data2);
            }
            #else
            stb_splitpath(fname, files[i], STB_FILE);
            stbi_write_png(stb_sprintf("output/%s.png", fname), w, h, 4, data, w*4);
            #endif
            free(data);
         }
         if (failed) {
            int j;
            printf("FAILED: ");
            for (j=0; j < stb_arr_len(failed); ++j)
               printf("%s ", failed[j]);
            printf(" -- %s\n", files[i]);
         }
      }
      printf("Tested %d files.\n", i);
   }
   return 0;
}
Beispiel #15
0
/***
Save a texture to a file.
@function :save
@tparam string filename path to the file to save the texture to
@tparam[opt=TYPE_PNG] number type type of the image to save. Can be TYPE_PNG or TYPE_BMP
@treturn[1] boolean true on success
@treturn[2] boolean `false` in case of error
@treturn[2] string error message
*/
static int texture_save(lua_State *L) {
	texture_userdata *texture = luaL_checkudata(L, 1, "LTexture");
	const char* path = luaL_checkstring(L, 2);
	u8 type = luaL_optinteger(L, 3, 0);

	int result = 0;
	if (type == 0) { // PNG
		FILE* file = fopen(path, "wb");
		if (file == NULL) {
			lua_pushboolean(L, false);
			lua_pushstring(L, "Can open file");
			return 2;
		}
		png_structp png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
		png_infop infos = png_create_info_struct(png);
		setjmp(png_jmpbuf(png));
		png_init_io(png, file);

		png_set_IHDR(png, infos, texture->texture->width, texture->texture->height, 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
		png_write_info(png, infos);

		png_bytep row = malloc(4 * texture->texture->width * sizeof(png_byte));

		for(int y=0;y<texture->texture->height;y++) {
			for (int x=0;x<texture->texture->width;x++) {
				((u32*)row)[x] = __builtin_bswap32(sf2d_get_pixel(texture->texture, x, y));
			}
			png_write_row(png, row);
		}

		png_write_end(png, NULL);

		fclose(file);
		png_free_data(png, infos, PNG_FREE_ALL, -1);
		png_destroy_write_struct(&png, &infos);
		free(row);

		result = 1;

	} else if (type == 2) { // BMP
		u32* buff = malloc(texture->texture->width * texture->texture->height * 4);
		if (buff == NULL) {
			lua_pushboolean(L, false);
			lua_pushstring(L, "Failed to allocate buffer");
			return 2;
		}
		for (int y=0;y<texture->texture->height;y++) {
			for (int x=0;x<texture->texture->width;x++) {
				buff[x+(y*texture->texture->width)] = __builtin_bswap32(sf2d_get_pixel(texture->texture, x, y));
			}
		}
		result = stbi_write_bmp(path, texture->texture->width, texture->texture->height, 4, buff);
		free(buff);
	
	} else {
		lua_pushboolean(L, false);
		lua_pushstring(L, "Not a valid type");
		return 2;
	}

	if (result == 0) {
		lua_pushboolean(L, false);
		lua_pushstring(L, "Failed to save the texture");
		return 2;
	}

	lua_pushboolean(L, true);
	return 1;
}