GithubHelp home page GithubHelp logo

frankodoom / libwebp.net Goto Github PK

View Code? Open in Web Editor NEW
26.0 3.0 4.0 17.19 MB

An asynchronous utility for encoding images to Google's .webp format using lossy and lossless compression algorithms.

Home Page: http://libwebp.azurewebsites.net/

C# 89.86% C 0.44% HTML 7.42% CSS 1.74% JavaScript 0.29% C++ 0.25%
webp asp-net-core image-compression encoding-library encoding-convertors google dotnet dotnet-standard file-format compress-images libwebp cwebp dotne dotnet-framework dotnet5

libwebp.net's Introduction

An asynchronous utility for encoding images to Google's .webp format. Seamlessly compress images to lossy and lossless formats in your .NET projects to improve network performance and reduce file size on disk. WebP generally has better compression than JPEG, PNG, and GIF and is designed to supersede them. You can see the library in action by using the webclient , your result will be downloaded into your browser.

Using the Library

General Usage

Below shows the basic use of the library using a console app.

 class Program
  {
    static async Task Main(string[] args)
     {

      // get file to encode
      using var file = new FileStream(@"C:\Users\fodoo\Desktop\logo.png", FileMode.Open);

      // copy file to Memory
       using var ms = new MemoryStream();
       await file.CopyToAsync(ms);
          
       //setup configuration for the encoder
       var config = new WebpConfigurationBuilder()
                       .Output("output.webp")
                       .Build();
                       
       // create an encoder and pass in the configuration
        var encoder = new WebpEncoder(config);

       // start encoding by passing your memorystream and filename      
       var output = await encoder.EncodeAsync(ms, Path.GetFileName(file.Name));

       /* your converted file is returned as FileStream, do what you want download,
          copy to disk, write to db or save on cloud storage,*/  
             
        Console.WriteLine($"Your output file : {Path.GetFileName(output.Name)}");
        Console.WriteLine($"Length in bytes : {output.Length}");
      }
   }

Asp.Net Core

Below demonstrates how the library is used in Asp.Net Core to convert uploaded images. This library is currently supported only in Windows Environments.

 public async Task<IActionResult> UploadAsync(IFormFile file)
       {

           if (file == null)
               throw new FileNotFoundException();

           //you can handle file checks ie. extensions, file size etc..
           
           //creating output file name
           // your name can be a unique Guid or any name of your choice with .webp extension..eg output.webp
           //in my case i am removing the extension from the uploaded file and appending
           // the .webp extension
           var oFileName = $"{Path.GetFileNameWithoutExtension(file.FileName)}.webp";

           // create your webp configuration
           var config = new WebpConfigurationBuilder()
              .Preset(Preset.PHOTO)
              .Output(oFileName)
              .Build();
           
           //create an encoder and pass in your configuration
           var encoder = new WebpEncoder(config);
           
          //copy file to memory stream
           var ms = new MemoryStream();
                    file.CopyTo(ms);
           
           //call the encoder and pass in the Memorystream and input FileName
           //the encoder after encoding will return a FileStream output
           
           //Optional cast to Stream to return file for download
           Stream fs = await encoder.EncodeAsync(ms, file.FileName);

           /*Do whatever you want with the file....download, copy to disk or 
             save to cloud*/

           return File(fs, "application/octet-stream", oFileName);
       }   

[Coming SOON!!!] Asp.Net Core MiddleWare

Libewebp.Net.Middleware is a separate package that depends on Libewebp.Net and allows you to inject image compression in your Asp.Net pipeline. This middleware will compress your specified image types using lossy and lossless angorithms.

Advanced Encoding

The encoder contains a lot advanced parameters. LibWebP.Net supports libWebp's advanced encoding API which can be used to better balance the trade-off between compression efficiency and processing time. You can get access to the advanced encode parameters by adding the various options below to your WebpConfigurationBuilder

  // create your WebP Configuration using fluent builder 
           var configuration = new WebpConfigurationBuilder()
                .Output("image.webp")
                .Preset(Preset.DEFAULT)
                .QualityFactor(200)
                .AlphaQ(10)
                 //.... add more advanced options//
                .Build();
              

Options

These options are currently supported in the library, use it to manipulate the compression algorithm for your desired output.

Option Description
AlphaQ(int value) transparency-compression quality (0..100)
CompressionMethod(int value) compression method (0=fast, 6=slowest)
Lossless() encode image losslessly
Preset(string value) one of default, photo, picture, drawing, icon, textd
QualityFactor(float value) quality factor (0:small..100:big)

Licence

Copyright 2021 

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

libwebp.net's People

Contributors

frankodoom avatar thekojopatrick avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

libwebp.net's Issues

Access to the path 'C:\Windows\TEMP\cwebp.exe' is denied.

I got this error when deploy code to hosting service (it works well on Azure)
In some cases, path0 has value "'C:\Windows\TEMP" and the user account don't have permission to read/write to this folder
// Get user temp directory
var path0 = Path.GetTempPath();

Is there anyway to config the temp folder?

multiple requests

I get an exception "The process cannot access the file 'C:...\AppData\Local\Temp\cwebp.exe' because it is being used by another process. ",when I had multi request
but I don't have any exception when use cwebp.exe with command line
do you have any option for support multi request ?

Centos 7 Error convert

Libwebp.Net.errors.CommandExecutionException: LibWebP.Net CommandExecutor Shell Failed: An error occurred trying to start process '/tmp/cwebp.sh' with working directory '/var/www/vhosts/xremaps.com/NetCore'. Permission denied

Hello, I encountered the above problem.
I will be glad if you help

Centos7 operating system

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.