Giter Site home page Giter Site logo

kleisauke / net-vips Goto Github PK

View Code? Open in Web Editor NEW
383.0 15.0 32.0 28.44 MB

.NET binding for libvips.

Home Page: https://kleisauke.github.io/net-vips/

License: MIT License

C# 99.62% PowerShell 0.12% Shell 0.24% Dockerfile 0.02%
libvips image-processing pinvoke bindings dotnet mono

net-vips's Introduction

NetVips

NuGet CI status (x64 Linux, macOS and Windows) CI status (Linux ARM64v8) CI status (NetVips nightly packaging)

This NuGet package provides a .NET binding for the libvips image processing library.

This binding passes the vips test suite cleanly with no leaks on Windows, macOS and Linux.

We have formatted docs online here:

https://kleisauke.github.io/net-vips/

How it works

Programs that use NetVips don't manipulate images directly, instead they create pipelines of image processing operations building on a source image. When the end of the pipe is connected to a destination, the whole pipeline executes at once, streaming the image in parallel from source to destination a section at a time.

Because NetVips is parallel, it's quick, and because it doesn't need to keep entire images in memory, it's light. For example, the NetVips benchmark:

NetVips.Benchmarks

Loads a large image, shrinks by 10%, sharpens, and saves again. On this test NetVips is around 20 times faster than Magick.NET and 3 times faster than ImageSharp.

The libvips documentation has a chapter explaining how libvips opens files which gives some more background.

Supported platforms

  • .NET Framework 4.5.2 and higher
  • .NET Standard 2.0 and higher
  • Mono

Install

You need the libvips shared library on your library search path, version 8.2 or later. There are separate NuGet packages that will contain the pre-compiled libvips binaries for the most common platforms (see this repo for details):

NuGet Package1
Windows 64-bit NetVips.Native.win-x64-badge
Windows 32-bit NetVips.Native.win-x86-badge
Windows ARM64 NetVips.Native.win-arm64-badge
Linux x64 glibc2 NetVips.Native.linux-x64-badge
Linux x64 musl3 NetVips.Native.linux-musl-x64-badge
Linux ARM64v8 glibc2 NetVips.Native.linux-arm64-badge
Linux ARM64v8 musl3 NetVips.Native.linux-musl-arm64-badge
Linux ARMv7 NetVips.Native.linux-arm-badge
macOS x64 NetVips.Native.osx-x64-badge
macOS ARM644 NetVips.Native.osx-arm64-badge

1 The version number of these NuGet packages is in sync with libvips' version number.
2 Uses glibc as the standard C library (Ubuntu, Debian, etc).
3 Uses musl as the standard C library (Alpine, Gentoo Linux, etc).
4 Requires .NET 6.0 or higher.

Then just install this package, perhaps:

Install-Package NetVips

To test your install, try this test program:

if (ModuleInitializer.VipsInitialized)
{
    Console.WriteLine($"Inited libvips {NetVips.Version(0)}.{NetVips.Version(1)}.{NetVips.Version(2)}");
}
else
{
    Console.WriteLine(ModuleInitializer.Exception.Message);
}
Console.ReadLine();

If NetVips was able to find the libvips shared library, you should see:

Inited libvips [VERSION_NUMBER]

However, if you see something else, NetVips was unable to initialize libvips. This can happen for a variety of reasons, even though most of the times it's because NetVips was not able to find libvips or due to x86/x64 architecture problems:

Inner exception HRESULT Solution
DllNotFoundException 0x8007007E Make sure to add the bin folder of the libvips Windows build to your PATH environment variable (if you wish to not use the separate NuGet packages).
BadImageFormatException 0x8007000B Make sure when you target the AnyCPU platform the Prefer 32-bit option is unchecked. Or try to target x64 instead.

Example

using NetVips;

using var im = Image.NewFromFile("image.jpg");

// put im at position (100, 100) in a 3000 x 3000 pixel image,
// make the other pixels in the image by mirroring im up / down /
// left / right, see
// https://www.libvips.org/API/current/libvips-conversion.html#vips-embed
using var embed = im.Embed(100, 100, 3000, 3000, extend: Enums.Extend.Mirror);

// multiply the green (middle) band by 2, leave the other two alone
using var multiply = embed * new[] { 1, 2, 1 };

// make an image from an array constant, convolve with it
using var mask = Image.NewFromArray(new[,]
{
    {-1, -1, -1},
    {-1, 16, -1},
    {-1, -1, -1}
}, 8);
using var convolve = multiply.Conv(mask, precision: Enums.Precision.Integer);

// finally, write the result back to a file on disk
convolve.WriteToFile("output.jpg");

net-vips's People

Contributors

darkle avatar dependabot[bot] avatar jcupitt avatar kleisauke avatar randyridge 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  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  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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

net-vips's Issues

Unable to load PDF files in dotnet core 2.1 projects using libvips 8.6.5 (global installation) and NetVips 1.0.4

Hi there,

today I again got a problem loading PDF files. But this time it's using NetVips in .NET Core 2.1 projects. :D

My test scenario to reproduce:

  1. Create a .NET 4.6.2 console app and a .NET Core 2.1 console app.
  2. In both install NetVips 1.0.4 via nuget and set <UseGlobalLibVips>true</UseGlobalLibVips> in the .csproj file. (Our global libvips installation is libvips 8.6.5 downloaded from the libvips project page.)
  3. Load a PDF file in the static Main method
internal class Program
{
	private static void Main(string[] args)
	{
		NetVips.Base.VipsInit();
		var vipsImage = NetVips.Image.NewFromFile(@"pdf1.pdf");
	}
}
  1. In .NET 4.6.2 this works without any problems. Using .NET Core 2.1 the is not a known fileformat exception pops up.

NetVips.VipsException:
'unable to load from file Q:\TestFactory\testdaten\bilder+audio+pdf\bilder\bildformate\pdf1.pdf
VipsForeignLoad: "Q:\TestFactory\testdaten\bilder+audio+pdf\bilder\bildformate\pdf1.pdf" is not a known file format

Is there something special to consider using .NET Core? Maybe I'm just missing a setting.

Thank you very much in advance. :)

Re: Using Net-Vips in .Net 4.5 project

Hello,

I've been trying to use the Net-Vips solution in .Net 4.5

Is there a way for Net-Vips to use the Vips dll files without setting the Environment Path.

Thanks

John Munro

x86 Compatibility

Hi Kleis,

Have you tested your wrapper with a win32 build of vips 8.6.4?
I've run a sample app with UseGlobalLibvips=true and pointing to the following: http://www.rollthepotato.net/~john/vips-dev-w32-8.6.4.zip

All calls are failing up front. It seems Operation.GetArgs() is getting garbage when dereferencing arguments struct.

Our platform is x86 only unfortunately.

Application crash at writing to png file

Hi,
If I try to save to a PNG file NetVips crashes and the result file has 0 bytes. There is no exception and no warning showing up.

Sample code:

var image = Image.NewFromFile("test.png"); // load whatever file you want
image.Pngsave("result.png"); // 0 bytes result file 

The error seems to occur in calling VipsOperation.VipsCacheOperationBuild(op); in Operation.cs, line 265.

Using vips.exe from Windows PowerShell works like expected:

.\vips.exe pngload grayscale.png png.v
.\vips.exe pngsave png.v result.png

I could reproduce this error using libvips 8.6.3, 8.6.4, 8.6.5 and 8.5.9.

Do you have any idea what could be causing this strange behavior?

Thank you in advance.

Question: get percentage of progress in dzsave

Hi!
Thx so much for netVips!!
I would like to use dzsave. Is it possible to pass a C# Action to get the percentage of the process?
I would like to show the progress on the console or in a Windows desktop program.

Thanks

Martin

Using MozJpeg options

Hi! I am experimenting with NetVips to do cropping, scaling, and high compression progressive JPEG encoding for a web application. I am trying to use JpegsaveBuffer with all the options that reduce file size

var bytes = image.JpegsaveBuffer(q: quality, optimizeCoding: true, interlace: true, trellisQuant: true, overshootDeringing: true, optimizeScans: true);

When I run this I get the following output.

(NetVips:21948): VIPS-WARNING **: 10:29:07.489: ignoring trellis_quant

(NetVips:21948): VIPS-WARNING **: 10:29:07.490: ignoring overshoot_deringing

(NetVips:21948): VIPS-WARNING **: 10:29:07.491: ignoring optimize_scans

I am using NetVips v1.0.7 and NetVips.Native.win-x64 v8.7.4. I tried replacing the libjpeg file with a build of mozjpeg v3.2 as provided by this project but it did not help.

My highest priority is file size so being able to use these options is important. Any advice?

Thank you!

Installation and execution of NetVips

Hi I am trying to get netvips working here on windows.Will this work?

Do I need to set up Environment Variables first?

I get this

ibvips zip file not in download directory. Downloading now ...
Downloading file: https://github.com/jcupitt/libvips/releases/download/v/vips-.zip

which of course fails

All the tests fail.

Not sure where to put the downloaded vips folder?

System.TypeInitializationException : The type initializer for '' threw an exception.
[02/05/2018 13:30:36 Informational] [xUnit.net 00:00:01.3574786] ---- System.DllNotFoundException : Unable to load DLL 'libvips-42.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
[02/05/2018 13:30:36 Informational] [xUnit.net 00:00:01.3575698] Stack Trace:
[02/05/2018 13:30:36 Informational] [xUnit.net 00:00:01.3576566] at NetVips.Tests.TestsFixture..ctor()
[02/05/2018 13:30:36 Informational] [xUnit.net 00:00:01.3577459] ----- Inner Stack Trace -----
[02/05/2018 13:30:36 Informational] [xUnit.net 00:00:01.3578316] at NetVips.Internal.Vips.VipsInit(String argv0)
[02/05/2018 13:30:36 Informational] [xUnit.net 00:00:01.3579297] C:\Users\Martin_Sarosi\Downloads\net-vips-master\src\NetVips\ModuleInitializer.cs(13,0): at NetVips.ModuleInitializer.Initialize()
[02/05/2018 13:30:36 Informational] [xUnit.net 00:00:01.3580023] at .cctor()

Any help

Join RGB channels into image

Using NetVips 1.0.7 with NetVips.Native 8.7.4.

image = imageR.Bandjoin(imageG).Bandjoin(imageB)

Resulted image Interpretation is 'b-w'. The only way for me to write correct image to file is to use Tiffsave(). Both Pngsave() and Webpsave() results in imageR as r,g and b channels and imageG, imageB as transparency. Am I doing something wrong here?
Also, is there a way to save tiff with 4th band as separate alpha channel, not as transparency?

Output Mosaic Image is White when using Globalbalance

Hi,

I am using Mosaic with Global balance to merge images. Only using Mosaic merge images but using Globalbalance makes the ouput Image white? The resolution of two source images is 1600x1200, and I want to overlap vertical on 180 px.

Below is my code:

        var image = Image.NewFromFile("source1.tif");
        var secondaryImage = Image.NewFromFile("source2.tif");
        Image mosaicedImage = image.Mosaic(secondaryImage, "vertical", 0, 1020, 0, 180);

        var ouptutImage = mosaicedImage.Globalbalance();
        ouptutImage.WriteToFile("output.tif");

Any suggestions?

Unable to delete original image file after calling NetVips.Image.Tiffsave

Hi,

I encounter errors trying to delete an input JPEG file after saving it to a TIFF file by calling NetVips.Image.Tiffsave(). Although Internal.GObject.GObjectUnref() and Internal.VipsObject.VipsObjectUnrefOutputs() are called it seems that not all handles are released.

Are there any additional steps I have to take, to fully release handles on the input image?

I'm using libvips 8.6.3 and NetVips 1.0.2. If you need any further information just let me know.

Thank you in advance.

Write string EXIF-tags with libvips

Hi,

I've got a problem with writing meta data to a JPEG file. I suppose this must be because of a datatype mismatch.

Here's a little example program, where I experience this error:

var vipsImage = NetVips.Image.NewFromFile("test.jpg"); // Load iamge

System.Console.WriteLine("Old orientation: " + vipsImage.Get("orientation"));
vipsImage.Set("orientation", 2); // Change orientation
System.Console.WriteLine("New orientation: " + vipsImage.Get("orientation"));

System.Console.WriteLine("Old key words: " + vipsImage.Get("exif-ifd0-XPKeywords"));
vipsImage.Set("exif-ifd0-XPKeywords", "test keyword"); // Change key words
System.Console.WriteLine("New key words: " + vipsImage.Get("exif-ifd0-XPKeywords"));

vipsImage.Jpegsave("result.jpg"); // Write to file

var reloadedImage = NetVips.Image.NewFromFile("result.jpg"); // Reload file

System.Console.WriteLine("Orientation after reload: " + reloadedImage.Get("orientation"));
System.Console.WriteLine("Key words after reload: " + vipsImage.Get("exif-ifd0-XPKeywords"));

(Note: For the above code snippet to work, the Tags field in Properties => Details of the loaded JPEG file must at least have one tag set. Otherwise, of course, vipsImage.Get("exif-ifd0-XPKeywords") will fail)

and the corresponding output:

Old orientation: 1
New orientation: 2
Old key words: Test-Tag (Test-Tag, Byte, 18 components, 18 bytes)
New key words: test keyword
Orientation after reload: 2
Key words after reload: Test-Tag (Test-Tag, Byte, 18 components, 18 bytes)

As you can see, I'm able to set a new orientation in meta data and after saving the file to disk (doesn't matter if I use Jpegsave or WriteToFile) and reloading the saved file again, the orientation still has my changed value but the exif-ifd0-XPKeywords field doesn't.
Now my guess is, this behavior is caused by a type mismatch of the exif-ifd0-XPKeywords field and the string i try to save into it. But the only hint I have is the different output of "Old keywords" and "New key words". Looking at the byte information in the "Old key words"-output i suppose i have to save the "test keyword"-string in a different way. But I don't know how. And also i don't know why, because before saving the image to disc, the changes seem to have an effect.

By debugging I saw that the type of this field is GValue.RefStrType and the part of the method GValue.Set() for GValue.RefStrType equals the part for GValue.GStrType while the GValue.Get() method differs at this point.

Now my question: Is this an error in NetVips or is the error in front of my keyboard? :)

I hope my problem is understandable and I'm thankful for any hint on how to properly save key words in the exif data.
If you need any further information, don't hesitate to ask.

Thank You

An unhandled exception of type 'System.TypeInitializationException' occurred in System.Windows.Forms.dll

Hi Kleis,

I've been trying to solve this issue myself for a few days and still don't know how.
The steps I've done today:

  1. Install a new copy of Windows 10 64-bit in Virtualbox
  2. Install Visual Studio Community and choose only C# Form Application Development.
  3. Start Visual Studio and create a Console Application, install NetVips 1.0.3 from Nuget manager in the Reference section.
  4. Paste the test code from net-vips README to main() function, using NetVips and build.

The error will stop the execution.

Any steps I missed?
Thank you.

issue with Image.Reduce()

When I provide anything less than 1.0 is not working it throw exception - reduce: parameter hshrink not set. being double it should accept less than 1.0 % as well.

NetVips.Image resize = tile.Reduceh(0.581);

Optimiser bug in libgsf

Hello,
I have noticed that sometimes, calls to Dzsave produce the following exception :

Exception= System.AccessViolationException: Tentative de lecture ou d'écriture de mémoire protégée. Cela indique souvent qu'une autre mémoire est endommagée (i.e : Attempt to read or write protected memory. This often indicates that another memory is damaged.) à NetVips.Internal.VipsOperation.VipsCacheOperationBuild(Operation operation) à NetVips.Operation.Call(String operationName, VOption kwargs, Object[] args) à NetVips.ExtensionMethods.Call(Image image, String operationName, VOption kwargs, Object arg) à NetVips.Image.Dzsave(String filename, String basename, String layout, Nullable'1 pageHeight, String suffix, Nullable'1 overlap, Nullable'1 tileSize, Nullable'1 centre, String depth, String angle, String container, Nullable'1 properties, Nullable'1 compression, Nullable'1 strip, Double[] background)

It's quite hard to figure out when and why it happens. These exceptions generally lead the whole process to a crash (even with . From what I've observed, once the process has successfully produced one pyramid, the following ones will be OK. It happened on several hosts, which exclude an hardware memory issue or something host related.

This happens with 32bits release of LibVips but could be reproduced with the 64bits release as well (with code that allocates memory before calling NetVips to get closer to real life conditions). Maybe this could be related to the amount of available memory for the thread. Anyway, pushing the limits with memory usually lead to a more classic (and sympathetic) exception (like "not enough memory for..." which is perfect)... But sometimes, I get this deadly low level AccessViolationException which make the whole process unstable and finally crash it down).

I'll try to upgrade NetVips and LibVips to the latest releases (who knows...). But if it's something that you already experienced, I'd be interested in a hint :-)

Thanks for your attention

Dzsave not embeding srgb or tinysrgb profile to tile

Hello, I m trying to get the srgb or tinysrgb profile to be embedded in tiles but without success.

using (var image = Image.NewFromFile(@"C:\dz\dz 2.jpg"))
            {
                image.Dzsave(@"C:\dz\dz", basename: "dz",
                suffix: ".jpg[Q=78,optimize_coding=1,strip=1,profile=srgb,no_subsample=0]", container: "fs");
            }

or

using (var image = Image.NewFromFile(@"C:\dz\dz 2.jpg"))
            {
                image.Dzsave(@"C:\dz\dz", basename: "dz",
                suffix: ".jpg[Q=78,optimize_coding=1,strip=1,profile=C:/dz/tinyrgb.icc,no_subsample=0]", container: "fs");
            }

is it possible to do it?

Saving .svs-file as tiles using Dzsave

Hi,
Is saving .svs-files as tiles using Dzsave implemented?

I have tried the following code which fails:
using System;
using NetVips;

namespace ConsoleApp3
{
class Program
{
static void Main()
{
string source = "C:\SourceFolder\2590310.svs";
NetVips.Image exampleobject = Image.NewFromFile(source);
exampleobject.Dzsave("c:\outputfolder\");

    }
}

}
Kindcregards,
Kai-Inge
image

NewFromBuffer causes GLib-ERROR with x86 libvips

Hi @kleisauke, thanks a ton for this libvips wrapper. I've learned a lot from reading your correspondence with @jcupitt.

Based on the advice in https://images.guide/, I'm currently reimplementing an image optimization pipeline with libvips at the core. Unfortunately, the larger program that this is a part of references other native x86 assemblies so for now I'm working with x86 libvips.

The x86 3-4GB memory limit seems to be causing an error that looks like (NetVips:17212): GLib-ERROR **: 11:19:21.666: /data/mxe/tmp-glib-i686-w64-mingw32.shared/glib-2.59.0/glib/gmem.c:105: failed to allocate 39493103 bytes.

image

I reproduced this issue in an isolated project and included large and small test images. https://github.com/jjonesrs/NetVipsLeakTest

Here it is inline:

byte[] imageBytes = File.ReadAllBytes(@"large-test-image.png");
//byte[] imageBytes = File.ReadAllBytes(@"small-test-image.jpg");

Base.LeakSet(1);

Operation.VipsCacheSetMax(0);
Operation.VipsCacheSetMaxFiles(0);

for (int i = 0; i < 1000000; i++)
{
    using (Image img = Image.NewFromBuffer(imageBytes))
    {
        Console.WriteLine(img);
    }
}

The above small snippet might look unrealistic, but it intentionally doesn't do any more than call Image.NewFromBuffer() on the source image to serve as a test of loading from a buffer in rapid succession. Loading from a file understandably does not exhibit the same memory patterns, but I'd highly prefer not to pull images from S3, save them to local disk, then risk file lock contention on delete.

I would expect the using ... statement to call Dispose() and signal to libvips to free the native memory at some point before the GLib crash, but it doesn't seem to have any effect.

I don't think that NetVips or libvips is strictly leaking, but it looks like maybe libvips isn't freeing images fast enough to keep up with the low x86 memory limit. Testing under x64, I can't reproduce the GLib error, but I do observe (in my opinion) high memory usage of 2-4GB.

I've included two memory profiles from JetBrains dotMemory leading up to the crash.

large-test-image.png:
image

small-test-image.jpg:
image

Question: How to write part of image to another image?

Hello. I have the following code on c#, using System.Drawing and System.Drawing.Imaging namespaces:

//read the input image
Image inputImage = Image.FromFile(inputFileName);

Then in foreach loop I crop that image to tiles:

//inside foreach
using (Bitmap outputImage = new Bitmap(TileSize, TileSize))
{
   using (Graphics graphics = Graphics.FromImage(outputImage))
   {
      graphics.DrawImage(inputImage,
                         new Rectangle(writeXPos,
                                       writeYPos,
                                       wirteXSize,
                                       writeYSize),
                         new Rectangle(readXPos,
                                       readYPos,
                                       readXSize,
                                       readYSize),
                         GraphicsUnit.Pixel);
   }

   outputImage.Save(outputFileName, ImageFormat.Png);
}

That works fine with little images, but when I'm trying to work with huge tiffs (like 4gb size and 20.000 x 20.000 pixel resolution bigtiff for example) the inputImage can not be initialized. So I tried NetVips in this purpose. It seems to read and write fast and successful:

using (Image inputImage = Image.Tiffload(inputFileName))
{
   using (Image outputImage = inputImage.Crop(readXPos, readYPos, readXSize, readYSize))
   {
      outputImage.Pngsave(outputFileName);
   }
}

But how to write that cropped part of inputImage to exact point and size in another image (in coordinates writeXPos and writeYPos and size of writeXSize and writeYSize. writeXSize and writeYSize are not equal to readXSize and readYSize - the input image is automatically resized to new sizes, and if not full image is filled (image resolution is TileSize x TileSize) then the other parts of image are transparent)?
Thanks in advance for your reply.

UPD

Found out about Embed method. I'll update issue after I test it.

Jpeg library

I'm was just curious if the jpeg support is using turbo-jpeg

The road to version 1.0

Things that should be done before we could declare 1.0 (and publish as NuGet package), in no order:

  • More examples. 8dc026c, 1c6a631
  • How should we integrate VipsInit? It's kind of weird that we have to call it in every class. 76ea725
  • Need to handle the libvips error buffer. 5a683d5
  • Do we need a VipsException? 5a683d5
  • Leak testing. 52d4e90
  • Define auto-generated functions / properties in a separate file. 6951638
  • Is NLog still needed as dependency? 733d527
  • Cross-platform support with .NET Core.
  • Documentation / auto generated docs (Doxygen or DocFX?). fd66da5
  • AppVeyor integration.
  • Travis integration.
    • Setup. 33afeba
    • Test on OS X. 7175700
    • Investigate sporadic error:
      g_value_get_object: assertion 'G_VALUE_HOLDS_OBJECT (value)' failed
      GLib-GObject-CRITICAL **: g_object_ref: assertion 'G_IS_OBJECT (object)' failed
      (Fixed with: 52d4e90 and b1c1920. Restarted Travis build 15 times and did some stress testing on Docker with low memory)
  • Benchmarks (BenchmarkDotNet looks promising). dc90ab3, 0480c7f
  • Polish readme. fd66da5

If someone knows more tasks, please feel free to add them in the comments.

openslideload integration

I am getting an error for
NetVips.Image.Openslideload(fileName)

Exception thrown: 'NetVips.VipsException' in NetVips.dll
An unhandled exception of type 'NetVips.VipsException' occurred in NetVips.dll
no such operation openslideload
VipsOperation: class "openslideload" not found

Creating Conditional image for IFTHENELSE opreration

I could not figure out how a conditional image can be created where the image equals to the given color value in NetVips.
In pyvips I have done something like this:

color_tuple= (255, 0, 0)
result_img= (original_img == color_tuple).bandand().ifthenelse( 0, 100)

What might be the correct and efficient implementation of above statement in C#?

BadImageException

Just having the first tries with your wrapper, but I keep getting an exception, which I dont understand. I am trying to open Jpegs, Tiff, etc, but this error pops up (below) for this code:

Microsoft.Win32.OpenFileDialog openFileDlg = new Microsoft.Win32.OpenFileDialog();
openFileDlg.RestoreDirectory = true;

        bool? result = openFileDlg.ShowDialog();
        if (result == true)
        {


            var image = NetVips.Image.NewFromFile(openFileDlg.FileName);

grafik

Reading complete tiff image for RGB values

I am using below code to get RGB values of the image for further processing, and it takes so much time, is there any other way to read RGB values?

NetVips.Image image = NetVips.Image.Tiffload(@inputFilePath, access: Enums.Access.Random);

        for (y = 0; y < tile.Height; y++)
        {
            for (x = 0; x < tile.Width; x++)
            {
                    double[] db = tile.Getpoint(x, y);
            }
       }

Mosaic color is not correct after stitching

Hi,

I am currently stitching a 5x5 tiles image into a Mosaic.
The approach I am taking is to first Mosaic all verticals together (means create 5 vertical mosaics of 1x5) and then stitch the new vertical images horizontally to achieve final image.
The problem I am facing is that final mosaic is too bright on right side and too dark on left side.
Please find the Merged file on this link as it is around 300 MB after Merging.

Could you please help!

Question: Best way to load and save files from a buffer when file type is not known

I'm loading images from the IFormFile container. I'm not sure what the best way is to find the image type so that I can save the images in the original format they were uploaded in. IFormFile.ContentType might not be reliable. I'm aware that libvips sniffs the first few bytes when loading a file from disk, is there a way to replicate that behaviour in this library? Perhaps to sniff from the intermediary buffer I'm using to load the image.

Files are still locked after dispose/close

Hi,
I need to cleanup a file after having been "tumbnailed" with NetVips. But it seems that files are still locked depsite even outside the "using" blocks. Do I miss something ?

            using (var image = NetVips.Image.NewFromFile(fileClone))
            using (var thumb = image.ThumbnailImage(250)) {
                Console.WriteLine(thumb.Width);
                thumb.WriteToFile(string.Concat(fileClone, ".thumbnail.jpeg"));
            }

            File.Delete(fileClone);

If I comment the "thumb.WriteToFile" line, the file is no longer locked though and can be deleted. Seems to be related to WriteToFile.

I did try to explicitly call the "Close" method on both Image objects (in case it's not done ine the Dipose). Still no luck...

Thanks for your attention !

Question: use custom libvips build in /opt directory

Hi,
I built custom libvips with poppler-glib support.
These libraries are bundled and deployed to AWS Lambda using Lambda layer, so they are located in /opt/lib
I've tried to set LD_LIBRARY_PATH env, but still get

Unable to load shared library 'libvips.so.42' or one of its dependencies. In order to help diagnose loading problems, consider setting the LD_DEBUG environment variable: liblibvips.so.42: cannot open shared object file: No such file or directory

Since has been removed in the latest releases I cannot find a way to force NetVips to search LD_LIBRARY_PATH folders

Thanks in adnvance.

GDI Interop

I'm trying to use NetVips as a step in a System.Drawing.Bitmap based image processing pipeline. Eventually I want to move the whole pipeline over to NetVips but for now I am stuck using them together. I have been trying to find a fast way of creating a NetVips.Image from a Bitmap object but haven't been able to come up with a good solution. I was wondering if anyone knew of an example of this being done? Thanks for any help.

NetVips.Version(0) invalid

I apologize in advance if this is a newbie question, as I am still coming up the learning curve on using Visual Studio and C# (Net Core).
In the https://github.com/kleisauke/net-vips README.md, the installation instruction indicates that a test for a successful install of NetVips will result in the test program printing a valid version number.
However, NetVips.Version(0) does not resolve to a valid identifier/expression.
It looks like there is a NetVips.ModuleInitializer.Version, however, that is supposed to return a 3-byte Integer? (Note: the returned value is 0x080800; which matches 8.8.0 as expected.)
Is this simply a case where the method to retrieve the version number has changed? Or am I doing something wrong with how I've configured my project to use NetVips?

Thanks in advance!

Sharpen the image using Linear filter

Hi ,

I need to create sharpen image using linear filter.
I found the net-vips will create sharpen image using gaussian filter and i found this code in net vibs

/// Sigma of Gaussian
/// Flat/jaggy threshold
/// Maximum brightening
/// Maximum darkening
/// Slope for flat areas
/// Slope for jaggy areas
/// A new

The Problem statement is

Input i am getting for sharpen (image processing) of linear filter and its parameter are
Kernal Size : 5 and Strength:10 .

Kernel Size: Here, you adjust the filter kernel size. The filter kernel size indicates how many neighboring pixels from the source image are included in the calculation of a pixel in the filtered image.

Strength: Here, you set the weighting of the filter kernel. The higher the weighting, the better the contrast of the filtered image. However, an excessive weighting can lead to interfering effects, such as noise.

Using the above input need to create sharpen image using ney-vips library

can i use this net-vips library to create sharpen image

public Image Sharpen(double? sigma = default(double? ), double? x1 = default(double? ), double? y2 = default(double? ), double? y3 = default(double? ), double? m1 = default(double? ), double? m2 = default(double? ))

If Yes .How can i map or convert kernal and Strength inputs to above net-vips sharpen .
Is gaussian filter and Linear filter are same algorithm ?

How can i implement this ?

Thanks
Vinay

Dynamic libvips path ?

Hello,
We have several types of C# processes that might use NetVips (and therefore, libvips). Some of them are 64bits and some of them are 32bits, some are web services, some are windows services.

To deal with that, I try to add the appropriate libvips path to the PATH environement variable at run time and at the process level (EnvironmentVariableTarget), depending of the current process architecure.

The problem is that ModuleInitializer's "Initialize" method is called way before any other code... So it's hard to patch the path variable without modifying NetVips code itself.

Do you a know a proper way to deal with this kind of dynamic libvips path ?

Thanks for your attention,
Guillaume

Can't load pdf files

Hello,

I'm giving net-vips a shot to replace Magick.Net. Unfortunately, I'm stuck with PDF file loading.
I tried the following:

var image = Image.NewFromFile(fileUrl);
var thumbnail = image.ThumbnailImage(300);
thumbnail.WriteToFile(outputFile);

Where "fileUrl" is the full path to a pdf file (I tried a few different ones).
This sample code returns the following exception :

Exception non gérée : NetVips.VipsException: unable to load from file C:\Downloads\VIPS\1501750297.pdf
VipsForeignLoad: "C:\Downloads\VIPS\1501750297.pdf" is not a known file format

   à NetVips.Image.NewFromFile(String vipsFilename, Nullable`1 memory, String access, Nullable`1 fail, VOption kwargs)
   à LibVipsTest.Program.Main(String[] args) dans C:\DATA\SOURCES\CSHARP\LibVipsTest\LibVipsTest\Program.cs:ligne 25

Net-vips is referenced via Nuget.
I must be missing something. Could you please give me a hint ?

Windows 10 Pro
Project built with x64 target

NetVips.VipsException: unable to call openslideload

CMU-1_001.zip

Hello,
I'm trying to use NetVips function openslideload to read some svs images. I meet some problems. If the path of the picture has Chinese or the name of the picture is Chinese, an error will occur.
this error pops up (below) for this code:

            try
            {
                Image thumbnail = NetVips.Image.Openslideload(path);
            }
            catch (Exception e)
            {
                string errormessage = e.ToString();
            }

NetVips.VipsException: unable to call openslideload
openslide2vips: unsupported slide format

Thanks for your attention,
Rick

Question: copy bundled libvips to another directory

Is there possibility to set the directory for bundled libvips before runtime? I don't want to have all the dll's in my working directory, I'd prefer something like "Release/vips/".

<UseGlobalLibvips>true</UseGlobalLibvips>
<LibvipsDLLPath>C:\vips-dev-w64-web\bin</LibvipsDLLPath>

This just copies the vips in selected directory to the output directory. I can't set EnvironmentVariable this way:

private static void SetVipsPath()
{
    string executingAssemblyFile = Assembly.GetExecutingAssembly().GetName().CodeBase.Replace("file:///", null);
    string executingDirectory = Path.GetDirectoryName(executingAssemblyFile);
    string vipsPath = $"{Path.Combine(executingDirectory, "vips")};";
    Environment.SetEnvironmentVariable("PATH", vipsPath);
}

either, because libvips's Initializer is called before runtime and throws exception because can't find libvips in my output directory.

Thanks in advance for your reply!

Slower PNG save operation

Hi,
I need to save an image of dimension 4000X5000 in PNG format. Just opening a jpg file and saving it to png alone is too slow(8.874 secs) but saving the same file in V format takes 0.439 secs.
NetVips version = 1.0.7
Is there any way around to save png images quickly?
`stopwatch.Start();
string fname = @"D:\photo.jpg";
var image = NetVips.Image.NewFromFile(fname);
image.WriteToFile(@"D:\vips.v");
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);

        stopwatch2.Start();
        var image2 = NetVips.Image.NewFromFile(fname);
        image2.WriteToFile(@"D:\vips.png");
        stopwatch2.Stop();
        Console.WriteLine(stopwatch2.ElapsedMilliseconds);
        Console.ReadKey();`

Better way to write native files

Hello.
I'm using NetVips along with others projects on Linux. After building the project with NetVips.Native package, it writes Linux dependencies in "runtimes/linux-x64/native" directory.
However, another library writes its dependencies the same way and overrides some files. Because of that, NetVips in my application doesn't work, throwing the exception:

Message [string]:"Unable to load shared library 'libvips.so.42' or one of its dependencies. In order to help diagnose loading problems, consider setting the LD_DEBUG environment variable: liblibvips.so.42: cannot open shared object file: No such file or directory"

Probably the native binaries should be written the other way to avoid these conflicts?

How to make multi band image to Greyscale image?

Hi Team,

  When we use bitmap.WriteToMemory() and if that has multi-band and it each band data is written as separate image and it cause issue when I use the byte array values. is is possible to make multi-band image as Greyscale image? I hope there will be some solution for the same.

Many thanks in advance.

Regards
JK

Native nuget package

Currently, the net-vips Nuget contains just windows x86/x64, which does not help me - I'm developing on Mac and deploying to Debian (which has an outdated vips version).

It would be great if net-vips followed a similar strategy to SkiaSharp, where they now have a new Native Nuget that contains the target runtimes for win, osx, linux, etc.

https://github.com/mono/SkiaSharp/wiki/SkiaSharp-Native-Assets-for-Linux

The skia linux nuget:
https://www.nuget.org/packages/SkiaSharp.NativeAssets.Linux

What are your thoughts about adding something like this to the project?

Benchmarks and commentary

Loads a large tiff image, shrinks by 10%, sharpens, and saves again. On this test NetVips is around 15 times faster than Magick.NET and 6 times faster than ImageSharp.

ImageSharp doesn't support Tiff but you know this already.

I'm curious about the sharpening phase of the test. Passing .75F to the ImageSharp GaussianSharpen algorithm will create a kernel with a radius of 3. Does net-vips adjust the dimensions of the input kernel to match that radius when dividing by 8?

var mask = NetVipsImage.NewFromArray(new[,]

.GaussianSharpen(.75f));

The resize phase definitely differs. Both ImageSharp and Skia are using sampling algorithms that sample more surrounding pixels than the linear sampler used in the net-vips code. I cannot comment on Magick.NET implementation as I do not know the internals.

im = im.Reduce(1.0 / 0.9, 1.0 / 0.9, kernel: Enums.Kernel.Linear);

I absolutely love a bit of healthy competition and it's really nice to see others interested in the space.

High Memory Usage in Sequential Access Mode

Hi,
I was trying to get the Emboss like map from an PNG image of dimension: 15000X18000. When I tried with sequential access mode the memory usage is above 1 GB but in random access mode the memory usage is only 100MB. Is this natural or I am doing something wrong?I want to use sequential mode for faster operation with low memory usage, is this possible?
Windows 10 and NetVips version :: 1.1.0

// Opening 3 images to use Wrap in sequential mode
string filename = "D:\\A.png";
NetVips.Image img = NetVips.Image.NewFromFile(filename, access:Enums.Access.Sequential).Colourspace("b-w");
NetVips.Image imgOne = NetVips.Image.NewFromFile(filename, access: Enums.Access.Sequential).Colourspace("b-w");
NetVips.Image imgTwo = NetVips.Image.NewFromFile(filename, access: Enums.Access.Sequential).Colourspace("b-w");
            
var embossKernel = Image.NewFromArray(new[,]
                                {
                                    {0.0, 0.0, -1.0},
                                    {0.0, 0.0, 0.0},
                                    {1.0, 0.0, 0.0}
                                }, scale: 0.25, offset: 0);

// Creating Outline of an Image
var moveRight = imgOne.Wrap(x: 1, y: 0);
var moveUp = imgTwo.Wrap(x: 0, y: 1);
var outline = (moveRight - img).Abs() + (moveUp -img).Abs();
outline = outline.RelationalConst("more", new double[] {50}).Invert();

//Applying Kernel
outline = outline.Ifthenelse(255, 200).Gaussblur(2);
outline = (outline.Conv(embossKernel, precision: "float") + 128);
outline = (outline > 200).Ifthenelse(200, outline);

outline.WriteToFile("D:\\Carving.jpg");

Linux: NetVips.VipsException: unable to write to buffer VipsForeignSave: "��G��" is not a known buffer format

Hi,
I am unable to use Image.WriteToBuffer() in a Linux Docker image.

I'm passing in the extension like shown in the documentation:
imageBytes = img.WriteToBuffer(".png");

This works perfectly fine when running in Windows, but in Linux it throws an exception like "NetVips.VipsException: unable to write to buffer VipsForeignSave: "�� p��" is not a known buffer format".

Tested in both Ubuntu and Alpine Docker images, using the same libvips install/build steps as from here

Image.WriteToFile() works in Linux, but i'd prefer not to have to save things to temp files if i can avoid it

Writing image to byte array

Hi @kleisauke,

      I am using bitmap.WriteToMemory() to write it to byte array, Let me know is there anyway to write those image byte values to another object, using byte[] array throws exception if the array size exceeds int limit.  

Cropping using 4 corner points

If we try to Crop using 4 corners top and bottom with different width and height, by just providing topright, Topleft , width and height will provide wrongly clipped image

EX:
TopRight = ( 198, 195)
TopLeft = ( 359, 195)
BottomLeft = ( 339, 1612)
BottomRight =( 168, 1606)

will never work, just by using TopRight, topLeft

@jcupitt @kleisauke

Saving from PDF file to TIFF/JPEG crashes silently

Hi,

I've got a problem saving a loaded PDF file to a JPEG or TIFF file. Unfortunately the error seems to occur only in some special cases with vector PDF files.

The files:

In my case I've got a set of vector PDF files all created by Ghostscript 9.14 using the PDF24 PDF creator. All PDF files are in the PDF 1.4 format. One file can be saved as a JPEG/TIFF file, the others fail.
Unfortunately at the moment I'm not able to provide an example PDF file where this error occurs due to reasons of privacy protection...

My problem:

The following sample code crashes silently at calling WriteToFile().

var vipsImage = NetVips.Image.NewFromFile("test_input.pdf"); vipsImage.WriteToFile("test_output.jpg");

Details:

Including the NetVips project (master branch) directly into my C# project and debugging through each single step, reveals that the call of VipsOperation.VipsCacheOperationBuild(op); in Operation.cs, line 265 crashes silently with op being an Operation created by the call of NewFromName(operationName); in Operation.cs, line 187 where operationName is VipsForeignSaveJpegFile.
As mentioned in the beginning this also fails with an output filename ending with .tiff and therefore VipsForeignSaveTiffFile as operationName.

Question:

Unfortunately without an example file it may be hard to reproduce this error. But do you have any clue what could cause this error?

Edit:

I just tried to save the PDF file to the vips format by calling WriteToFile("test_vips.v");. This also leads to the error. Therefore i suppose the output format doesn't matter...

Thanks in advance for any help. :)

Loading PDF

Hi,

I'm trying to load PDF using net-vips, however I keep getting this error :

var vipsImage = NetVips.Image.NewFromFile(@"pdfFile.pdf");
unable to load from file pdfFile.pdf" is not a known file format

I understand I require poppler for the PDF support, but i'm not exactly sure, how to integrate poppler support to my vips code, any help is appreciated.
I included all the dll (including libpoppler-91) in the same folder as libvips, but no luck

Thanks

Auto-Generator?

Would you mind sharing which auto-generator you used to create this wrapper as well as it's source code?

I'm interested in creating another wrapper for another tool and I really like how you've created yours.

Thanks,
Darren

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.