Package: pyoxipng
pyoxipngPython wrapper for multithreaded .png image file optimizeroxipng(written in Rust). Usepyoxipngto reduce the file size of your PNG images.Jump to a sectionInstallationAPIoptimizeoptimize_from_memoryRawImageOptionsfilterinterlacestripdeflateDevelopmentLicenseInstallationInstall from PyPI:pipinstallpyoxipngImport in your Python code:importoxipngAPIoxipng.optimize(input, output=None, **kwargs)Optimize a file on disk.Parameters:input(str | bytes | PathLike)– path to input file to optimizeoutput(str | bytes | PathLike, optional)– path to optimized output result file. If not specified, overwrites input. Defaults to None**kwargs–OptionsReturnsNoneRaisesoxipng.PngError– optimization could not be completedExamples:Optimize a file on disk and overwriteoxipng.optimize("/path/to/image.png")Optimize a file and save to a new location:oxipng.optimize("/path/to/image.png","/path/to/image-optimized.png")oxipng.optimize_from_memory(data, **kwargs)Optimize raw data from a PNG file loaded in Python as abytesobject:Parameters:data(bytes)– raw PNG data to optimize**kwargs–OptionsReturns(bytes)– optimized raw PNG dataRaisesoxipng.PngError– optimization could not be completedExamples:data=...# bytes of png dataoptimized_data=oxipng.optimize_from_memory(data)withopen("/path/to/image-optimized.png","wb")asf:f.write(optimized_data)oxipng.RawImageCreate an optimized PNG file from raw image data:raw=oxipng.RawImage(data,width,height)optimized_data=raw.create_optimized_png()By default, assumes the input data is 8-bit, row-major RGBA, where every 4 bytes represents one pixel with Red-Green-Blue-Alpha channels. To interpret non-RGBA data, specify acolor_typeparameter with theoxipng.ColorTypeclass:MethodDescriptionoxipng.ColorType.grayscale(int | None)Grayscale, with one color channel. Specify optional shade of gray that should be rendered as transparent.oxipng.ColorType.rgb(tuple[int, int, int])RGB, with three color channels. Specify optional color value that should be rendered as transparent.oxipng.ColorType.indexed(list[[tuple[int, int, int, int]])Indexed, with one byte per pixel representing a color from the palette. Specify palette containing the colors used, up to 256 entries.oxipng.ColorType.grayscale_alpha()Grayscale + Alpha, with two color channels.oxipng.ColorType.rgba()RGBA, with four color channels.Parameters:data(bytes | bytearray)– Raw image data bytes. Format depends oncolor_typeandbit_depthparameterswidth(int)– Width of raw image, in pixelsheight(int)– Height of raw image, in pixelscolor_type([oxipng.ColorType, optional)– Descriptor for color type used to represent this image. Optional, defaults tooxipng.ColorType.rgba()bit_depth(int, optional)– Bit depth of raw image. Optional, defaults to 8Examples:Save RGB image data from a JPEG file, interpreting black pixels as transparent.fromPILimportImageimportnumpyasnp# Load an image file with Pillowjpg=Image.open("/path/to/image.jpg")# Convert to RGB numpy arrayrgb_array=np.array(jpg.convert("RGB"),dtype=np.uint8)height,width,channels=rgb_array.shape# Create raw image with sRGB color profiledata=rgb_array.tobytes()color_type=oxipng.ColorType.rgb((0,0,0))# black is transparentraw=oxipng.RawImage(data,width,height,color_type=color_type)raw.add_png_chunk(b"sRGB",b"\0")# Optimize and saveoptimized=raw.create_optimized_png(level=6)withopen("/path/to/image/optimized.png","wb")asf:f.write(optimized)Save with data where bytes reference a color palettedata=b"\0\1\2..."# get index datapalette=[[0,0,0,255],[1,23,234,255],...]color_type=oxipng.ColorType.indexed(palette)raw=oxipng.RawImage(data,100,100,color_type=color_type)optimized=raw.create_optimized_png()Methods:add_png_chunk(name, data)Add a png chunk, such asb"iTXt", to be included in the outputParameters:name(bytes)– PNG chunk identifierdata(bytes | bytarray)Returns:Noneadd_icc_profile(data)Add an ICC profile for the imageParameters:data(bytes)– ICC profile dataReturns:Nonecreate_optimized_png(**kwargs)Create an optimized png from the raw image data using the options providedParameters:**kwargs–OptionsReturns:(bytes)optimized PNG image dataOptionsoptimize,optimize_from_memoryandRawImage.create_optimized_pngaccept the following options as keyword arguments.Example:oxipng.optimize("/path/to/image.png",level=6,fix_errors=True,interlace=oxipng.Interlacing.Adam7)OptionDescriptionTypeDefaultlevelSet the optimization level to an integer between 0 and 6 (inclusive)int2fix_errorsAttempt to fix errors when decoding the input file rather than throwingPngErrorboolFalseforceWrite to output even if there was no improvement in compressionboolFalsefilterWhich filters to try on the file. Use Use enum values fromoxipng.RowFilterset[RowFilter]{RowFilter.NoOp}interlaceWhether to change the interlacing type of the file.Nonewill not change current interlacing typeInterlacing| NoneNoneoptimize_alphaWhether to allow transparent pixels to be altered to improve compressionboolFalsebit_depth_reductionWhether to attempt bit depth reductionboolTruecolor_type_reductionWhether to attempt color type reductionboolTruepalette_reductionWhether to attempt palette reductionboolTruegrayscale_reductionWhether to attempt grayscale reductionboolTrueidat_recodingIf any type of reduction is performed, IDAT recoding will be performed regardless of this settingboolTruescale_16Whether to forcibly reduce 16-bit to 8-bit by scalingboolFalsestripWhich headers to strip from the PNG file, if any. Specify withoxipng.StripChunksStripChunksStripChunks.none()deflateWhich DEFLATE algorithm to use. Specify withoxipng.DeflatersDeflatersDeflaters.libdeflater()fast_evaluationWhether to use fast evaluation to pick the best filterboolFalsetimeoutMaximum amount of time to spend (in milliseconds) on optimizations. Further potential optimizations are skipped if the timeout is exceededint | NoneNonefilterInitialize thefilterset with any of the followingoxipng.RowFilterenum options:oxipng.RowFilter.NoOpoxipng.RowFilter.Suboxipng.RowFilter.Upoxipng.RowFilter.Averageoxipng.RowFilter.Paethoxipng.RowFilter.Bigramsoxipng.RowFilter.BigEntoxipng.RowFilter.BruteinterlaceSetinterlacetoNoneto keep existing interlacing or to one of followingoxipng.Interlacingenum options:oxipng.Interlacing.Off(interlace disabled)oxipng.Interlacing.Adam7(interlace enabled)stripInitialize thestripoption with one of the following static methods in theoxipng.StripChunksclass.MethodDescriptionoxipng.StripChunks.none()Noneoxipng.StripChunks.strip(set[bytes])Strip specific chunksoxipng.StripChunks.safe()Strip chunks that won't affect rendering (all but cICP, iCCP, sRGB, pHYs, acTL, fcTL, fdAT)oxipng.StripChunks.keep(set[bytes])Strip all non-critical chunks except theseoxipng.StripChunks.all()Strip all non-critical chunksdeflateInitialize thedeflateoption with one of the following static methods in theoxipng.Deflatersclass.MethodDescriptionoxipng.Deflaters.libdeflater(int)Libdeflater with compression level [0-12]oxipng.Deflaters.zopfli(int)Zopfli with number of compression iterations to do [1-255]DevelopmentInstallRustInstallPython 3.8+InstallPipenvClone this repository and navigate to it via command linegitclonehttps://github.com/nfrasser/pyoxipng.gitcdpyoxipngInstall dependenciespipenvinstall--devActivate the dev environmentpipenv shellBuildmaturindevelopRun testspytestFormat codeblack .LicenseMIT