dlemstra / magick.net Goto Github PK
View Code? Open in Web Editor NEWThe .NET library for ImageMagick
License: Apache License 2.0
The .NET library for ImageMagick
License: Apache License 2.0
The current PixelCollection checks the bounds when a pixel is accessed. A new class should be added that does not check the bounds and PixelCollection should inherit from that class.
The hack itself described here http://www.openwall.com/lists/oss-security/2016/05/03/18
The ImageOptimizers now only support optimizing a file on disk. A new overload should be added that allows the optimization of a stream. The stream should support reading, writing and seeking because the original stream should be overwritten with the new optimized image. Because we only optimize JPG/PNG and GIF we don't need to pass in the format because we can determine that from reading the first few bytes.
Hello,
I would like to include support for Xamarin,
but I need a bit of guidance.
I am using Magick.NET to convert SVG to PNG. It works really well on local machine, but when I publish the project to Azure it fails to render PNG.
I have created simple web page to demonstrate the issue. You can check http://adforcent-staging.azurewebsites.net/test/convert to see the result of the input SVG (in textarea).
On local machine the code produces readable image (same as when I open SVG with Inkscape), but when the code is published, I do not see any text.
I am struggling for couple of days and with no progress. I cannot find any similar issues with Google.
Code is simple:
string svg = form["svg"]; // SVG from the form
byte[] SvgBytes = Encoding.ASCII.GetBytes(svg);
MagickReadSettings readSettings = new MagickReadSettings()
{
Format = MagickFormat.Svg,
};
using (MagickImage image = new MagickImage(SvgBytes, readSettings))
{
image.Format = MagickFormat.Png;
result = image.ToBitmap();
}
Am I the only one with this problems? I am using latest version of Magick.net (v7).
I would appreciate any hint on that subject.
Thank you in advance!
After trimming an image, clipping paths no longer mark the shapes of objects.
For a more detailed explanation, see my question at StackOverflow: http://stackoverflow.com/questions/43280835/how-can-i-trim-an-image-using-magick-net-keeping-clipping-paths-if-they-exist
When streams are being used all the data needs to be copied to an array. It would be nice if ImageMagick could be changed to use a function when bytes need to be read of written. Then only part of the data needs to be copied instead of all the data.
I'm using Magick.Net for a project and getting the following exception:
{"Failed to allocate memory for custom tag binary object (150965188 elements of 1 bytes each). `C:\..\TestThumbs\A2 YR11 WPP Grey.tif' @ error/tiff.c/TIFFErrors/572"}
The exception is thrown in the constructor (new MagickImage(filepath)). The image is 180MB, and while I'm building for Any CPU, prefer 32bit is set to true.
I'm using the 8-bit version of Magick.Net - could this be a colour space compatability problem? The TIF file is using 24bit colour depth.
Thanks
I have a basic black & white image, and I want to know the position of the black box.
The code is the following:
MagickImage myImage = new MagickImage(String.Format("{0}\\black_white.png", AppDomain.CurrentDomain.BaseDirectory));
var pixels = myImage.GetPixels().Where(p => p.ToColor() == MagickColor.FromRgb(0, 0, 0));
var minX = pixels.Min(p => p.X);
var minY = pixels.Min(p => p.Y);
var maxX = pixels.Max(p => p.X);
var maxY = pixels.Max(p => p.Y);
Debug.WriteLine("Min X : " + minX + " - Min Y : " + minY + " / Max X : " + maxX + " - Max Y : " + maxY); // print Min X : 528 - Min Y : 144 / Max X : 943 - Max Y : 729
var pixelCollection = myImage.GetPixels();
minX = -1;
minY = -1;
maxX = -1;
maxY = -1;
for (int i = 0; i < myImage.Height; i++)
{
for (int j = 0; j < myImage.Width; j++)
{
var pixel = pixelCollection.GetPixel(j, i);
if (pixel.ToColor() == MagickColor.FromRgb(0, 0, 0))
{
if (minX == -1)
minX = pixel.X;
else if (pixel.X < minX)
minX = pixel.X;
if (maxX == -1)
maxX = pixel.X;
else if (pixel.X > maxX)
maxX = pixel.X;
if (minY == -1)
minY = pixel.Y;
else if (pixel.Y < minY)
minY = pixel.Y;
if (maxY == -1)
maxY = pixel.Y;
else if (pixel.Y > maxY)
maxY = pixel.Y;
}
}
}
Debug.WriteLine("Min X : " + minX + " - Min Y : " + minY + " / Max X : " + maxX + " - Max Y : " + maxY); // print Min X : 264 - Min Y : 144 / Max X : 679 - Max Y : 729
I don't know why the LINQ version give me wrong results. Any ideas?
Hi,
I'm using magick net library to convert image from jpg/png image into tif. Besides conversion I need apply some transformation for image (Trim, SetColorProfile, Resize, etc.).
For most of images it works just well, but for some of them it throws error like:
IO error writing tag data. 'TIFFWriteDirectoryTagData' @ error/tiff.c/TIFFErrors/565.
This error not happens if during conversion skipped SetColorProfile step. Before similar error was for Trim, but we updated library from version "Magick.NET.Core-Q8 7.0.2.400", to "Magick.NET.Core-Q8 7.0.3.300", and it fixed problem, but now it happens for another operations. Stack trace does not told me reason of error:
"at ImageMagick.MagickImage.NativeMagickImage.WriteBlob(MagickSettings settings, UIntPtr& length)\r\n at ImageMagick.MagickImage.Write(Stream stream)\r\n at ImageMagick.MagickImage.ToByteArray()\r\n "
NOTE: Console tool of ImageMagick works for problematin image.
I prepared sample to reproduce the problem. https://github.com/inteno/ImageMagickTifError
I also created issue at Codeplex, because i'm not sure what is primary source.
https://magick.codeplex.com/workitem/1417
Hello
I need to convert PDF to jpg or png then convert it back to PDF.
I am using the examples from the documentation. nothing fancy.
But i find that the resulting pdf size is 3 times bigger than the original. I notice that the page containing in the orig PDF gets converted with the largest size. Maybe here i need to find a way to optimize it better?
What will be the best way to keep the PDF size as the original?
Thanks!
Roy
I need to remove transparency from a PNG and convert to BMP with white background. the commented out lines are things I have tried. it just keeps coming out transparent.
var image = blah.Item1;
var label = blah.Item2;
var drawblah = new Drawables().FillColor(Color.Black).TextAlignment(TextAlignment.Center).Gravity(Gravity.South).Font("BankGothic Md BT").FontPointSize(16).Text(50,105, label);
image.Settings.Density = new Density(DPI, DPI);
//image.AlphaColor = Color.White;
//image.VirtualPixelMethod = VirtualPixelMethod.Transparent;
//image.TransparentChroma(Color.White, Color.White);
//image.BackgroundColor = Color.White;
image.Draw(drawblah);
The code for Magick.NET.Web has not unit tests at the moment and they should be added. The code should also be refactored to make unit testing easier.
I encountered a very annoying bug with the Resize() method.
I need to call multiple times Resize() on a image, but the degradation is amplified on every call.
I've managed to make a simple reproduction:
MagickImage image;
using (image = new MagickImage(SampleFiles.FujiFilmFinePixS1ProJpg))
{
image.Resize(new Percentage(99));
image.Resize(new Percentage(99));
image.Resize(new Percentage(99));
image.Resize(new Percentage(99));
image.Resize(new Percentage(99));
image.Resize(new Percentage(99));
image.Resize(new Percentage(99));
image.Resize(new Percentage(99));
image.Resize(new Percentage(99));
image.Resize(new Percentage(99));
image.Resize(new Percentage(99));
image.Resize(new Percentage(99));
image.Resize(new Percentage(99));
image.Resize(new Percentage(99));
image.Resize(new Percentage(99));
image.Resize(new Percentage(99));
image.Resize(new Percentage(99));
image.Resize(new Percentage(99));
image.Write(SampleFiles.OutputDirectory + "FujiFilmFinePixS1Pro.resized.jpg");
}
You can make fewer calls but the degradation will be less visible.
The result:
My method look like this:
using (MagickImage icon = new MagickImage("temp/icon.png"))
{
icon.Rotate(-10);
icon.Write("temp/icon.png");
}
I've tried with
icon.BackgroundColor = MagickColors.Transparent;
icon.AlphaColor = MagickColors.Transparent;
to get white space away, but unsuccessful
Dim img As New ImageMagickObject.MagickImage
Call img.Convert("-resize", "390x", "-crop", "390x590+0+0", sourceImg, sourceImg)
I am currently using imageMagick com object and the above code. What would be the equivalent in Magick.net
Thanks
Hi,
I got error message when trying to load a TIF file. This only happens on specific file.
My code:
using (var magicImg = new MagickImage(path)) {
//
}
Sample file:
http://netghost.narod.ru/gff/sample/images/tiff/marbles.tif
http://netghost.narod.ru/gff/sample/images/tiff/index.htm
Hello,
I am trying to configure MagickNET log like this:
MagickNET.SetLogEvents(LogEvents.Cache | LogEvents.Exception | LogEvents.Resource);
MagickNET.Log += MagickNET_Log;
But in the actual log file i see all my specified events from enum + Pixel, Coder, Policy, Blob events.
How can i prevent these events from logging?
ImageMagick.Net 7.0.3.902 Already Repair CVE-2016-8707 ?
I wonder if I should move the code that reads the exif data to another project. On CodePlex the following issue was started: https://magick.codeplex.com/workitem/1424. I think it would be a good idea to add extra classes for the marker notes. And maybe even make parsing the exif data as good as exiftool. The current code is shared by ImageSharp and Magick.NET and maybe other libraries could also use it. When those classes are added it might be time to move the code. Maybe we could use this: https://github.com/drewnoakes/metadata-extractor-dotnet. But it would be nicer if that library would split parsing the data and reading it from image files into two libraries.
I'm trying to mix a JPG image with a monochromatic image generated with MagickImage:
using (MagickImage image = new MagickImage(String.Format("{0}\\FujiFilmFinePixS1Pro.jpg", AppDomain.CurrentDomain.BaseDirectory)))
{
using (MagickImage image2 = new MagickImage(new MagickColor(236, 236, 236, 255), image.Width, image.Height))
{
image.Composite(image2, CompositeOperator.Plus);
}
image.Write(String.Format("{0}\\result.png", AppDomain.CurrentDomain.BaseDirectory));
}
And it's not working, the result is the exact same JPG image.
It seems to work when
I understand IM has this built in via some pattern parameter, but I do not know how to pass this in via Magick.NET.
Or even a way to specify my own checkerboard pattern as a jpg and tile it?
Could you possibly assist? :)
when i convert a page of svg to pdf , it seems that magick.net use 90dpi as the dpi to convert the svg,but i want to change it to be 96dpi ,how can i do this? thanks
I am trying to resize an image of any size to tabloid (11" x 17") and converting to PDF. Without the resize I am getting clear pdf but when I do a resize the PDF quality vastly deteriorates.
Can you help me out on this issue ?
Testfile1_high_res7200by200_16bit_WithoutResize.pdf
Testfile1_high_res7200by200_16bit_WithResize.pdf
Note: In addition to resize, I am also doing other operations like adding border, rotating the image, etc. The file (Testfile1_high_res7200by200_16bit_WithoutResize.pdf), has all other changes applied other than resize.
When initializing an ImageMagick object, the following error is being thrown on MacOS:
System.DllNotFoundException: Unable to load DLL 'Magick.NET-Q16-x64.Native.dll': The specified module could not be found.
I am including "Magick.NET.Core-Q16": "7.0.3.502"
as a dependency.
The latest version has removed PngReadDefines.PreserveCorruptImage property - why is that? I was using it to handle opening PNG images that has bad CRC but actually still can be viewed normally.
Also, where did ResolutionX and ResolutionY go? Why such breaking changes increments only the minor version of the package?
I was using this piece of code to circle crop an image using a mask:
MagickImage image;
using (image = new MagickImage(SampleFiles.FujiFilmFinePixS1ProJpg))
{
image.VirtualPixelMethod = VirtualPixelMethod.Transparent;
image.Format = MagickFormat.Png;
using (var maskImage = new MagickImage(MagickColors.Black, image.Width, image.Height))
{
var diameter = maskImage.Width < maskImage.Height ? maskImage.Width : maskImage.Height;
int originY = (maskImage.Height - diameter) / 2 + diameter / 2;
int originX = (maskImage.Width - diameter) / 2 + diameter / 2;
maskImage.Draw(new IDrawable[]{
new DrawableFillColor(MagickColors.White),
new DrawableCircle(originX, originY, 0, originY)
});
image.Composite(maskImage, CompositeOperator.CopyAlpha);
}
image.Write(SampleFiles.OutputDirectory + "FujiFilmFinePixS1Pro.cropped.png");
Since Magick.NET 7.0.2.900 (Same result with 7.0.3.1, the version I'm trying to use), my image isn't cropped anymore:
Instead of:
Using any version since (and including) 7.0.0.104 produces a blank white image when trying to convert an SVG source to PNG or JPEG (or presumably any other rasterized image). The latest version I tried is 7.0.3.902 and it's still producing a blank image. To make sure it's not an issue with ImageMagick, I downloaded and installed version 7.0.4.0 and ran the following command:
magick.exe convert "C:\Test.svg" "C:\Test.png"
It correctly produced the expected PNG image. This leaves me to believe that the issue is with Magick.NET and how it's delegating to ImageMagick. The following code is what I've used with 7.0.0.103, but it doesn't working with 7.0.0.104+ and I don't know of any other way to make the conversion:
string value = "...";
byte[] bytes;
using (var memoryStream = new MemoryStream()) {
using (var streamWriter = new StreamWriter(memoryStream)) {
streamWriter.Write(value);
}
using (var magickImage = new MagickImage(memoryStream, new MagickReadSettings {
Format = MagickFormat.Svg
})) {
bytes = magickImage.ToByteArray(MagickFormat.Png24);
}
}
File.WriteAllBytes(@"C:\Test.png", bytes);
I'd appreciate any suggestions if I'm doing something wrong, or if it really is an issue with Magick.NET if it could be fixed. I've been using 7.0.0.103 and ignoring all updates solely because of this issue. I'm attaching a sample SVG for testing. This is being used inside of an ASP.NET MVC 5 web app on .NET 4.6.2. Thanks in advance!
Sorry if I am not supposed to ask questions here.
How can I load a tiff image which has couple of layers and then write it on HDD as a flatten image.
I tried this one and the result is fine, i will get an image with one layer which is the combination of all layers but I cannot get a flatten image. Actually i convert the image into PSD and then read the PSD and converet it to the original format which I think is not a good solution.
public void FlatTheLayeredTiff(string filePath)
{
var isMoreThanOneLayer = false;
var extention = Path.GetExtension(filePath).ToLower();
if (extention != ".tiff" && extention != ".tif") return;
using (var image = new MagickImage(filePath))
{
using (var stream = new MemoryStream())
{
image.Write(stream, image.Format);
using (var collection = new MagickImageCollection(stream))
{
if (collection.Count == 1) return;
}
}
var psdPath = filePath.Substring(0, filePath.LastIndexOf(".") + 1) + "psd";
image.Write(psdPath);
using (var im = new MagickImage(psdPath))
{
im.Format = image.Format;
im.Write(filePath);
}
}
}
I'm using the c# version of imagemagick. I just want to add transparent text to a white background. Seems easy enough in command line but can't figure out how to translate to c#. Any help would be appreciated. Thanks.
ImageMagick is already cross platform, will it be possible you to create NuGet package that is also cross platform?
Lets say I have the code below.
using (var image = new MagickImage())
{
image.Warning += MagickImage_Warning;
image.Read(currentFile);
}
If this tries to read a PNG that is partially corrupted then the method will just run without ever timing out. It also isn't throwing an exception or executing the warning event.
hi,it seems that I had met a bug when I transfer svg to png , when I transfer a svg to png,it seems that
i can not transfer japenese word with writing-modle:tb rightly in a svg ,
this is the svg file
I'm having issue with the Resize function.
When I process the image with C#, the resize() will give me the image with the worse quality when the image size is decrease from width and height are 2000 to 200 or lower then I use cmd "-resize"
My code is below
C#
MagickImage Small = fullsizeImg; MagickGeometry size_Small = new MagickGeometry(80, 80); size_Small.IgnoreAspectRatio = true; Small.Resize(size_Small);
cmd
convert input.jpg -resize 135 output.jpg
I tried AdaptiveResize() as well but the result is even worse.
Please check below.
This is generated from Resize()
Thanks!
Hello, the Resize function seems to have broken in the latest release "Magick.NET.Core-Q8": "7.0.3.300",
the program just gets stuck, i tried instantiating the geometry and sending it as a parameter and also just sending the sizes.
var geometry = new MagickGeometry(width, height);
image.Resize(geometry);
//image.Resize(width, height);
I dont get an exception at all, it just stops.
AdaptiveResize is working fine and I am using that in the mean time...
I'm currently using Magic.Net.Web for resizing my images when requested. Currently we are fetching the images we want to resize from a share. So far, no issues.
Currently we are investigating to move to the cloud and in this case we would like to make use of Blobstorage. This issue with this is inside the ImageOptimizerHandler. In this you need a fileName that is used to copy the image. So an url is not allowed here. So an extension that you are able to provide a stream instead of a file name would be great. You could check for a stream first and write this to your tempfolder if present. If not provided you can take the way it is currently working.
Let me know what you think.
Both MagickImage and MagickImageCollection should implement an interface to make testing easier. This also means that all calls that use a MagickImage should use an IMagickImage instead. And the tests that use a MagickImage should also use the IMagickImage interface.
Hi,
Is there a way to provide the same "-limit memory 500" via Magick.NET? Currently it's using 4+ gigs converting a 200 page PDF.
Thanks
This library would be very useful for people using Unity. Unity uses an old, .NET 3.5 equivalent version of Mono, so the .NET 4 version is incompatible.
I know it is possible with ImageMagick create text labels, or add text to images. It seems, that Magick.Net doesn't provide this useful features. Do you will implement this functionality in next versions?
I have updated my code with the latest version of Magick.NET (7.0.2.100).
I'm trying to crop an image with a circle and resize it. I made a sample reproduction code:
static void Main(string[] args)
{
MagickImage image;
using (image = new MagickImage(SampleFiles.FujiFilmFinePixS1ProJpg))
{
image = GenerateCircleImage(image);
image.Resize(300, 0);
image.Write(SampleFiles.OutputDirectory + "FujiFilmFinePixS1Pro.resized.jpg");
}
}
public static MagickImage GenerateCircleImage(MagickImage image)
{
using (var maskImage = new MagickImage(MagickColors.Black, image.Width, image.Height))
{
maskImage.Draw(new IDrawable[]{
new DrawableFillColor(MagickColors.White),
new DrawableCircle(300, 200, 100, 200)
});
image.VirtualPixelMethod = VirtualPixelMethod.Transparent;
image.Composite(maskImage, CompositeOperator.CopyAlpha);
}
return image;
}
I have two problems:
Thanks for the very useful lib.
How to apply automatically embedded color profile of an image?
I have an image, when I use:
using (var img = new MagickImage(path))
{
bmp = img.ToBitmap();
}
the color of image displayed incorrectly:
Before that, using .NET Bitmap, I can write:
bmp = new Bitmap(path, true);
Thank you
I ran into a weird issue with the GrantEveryoneReadAndExecuteAccess().
I deployed my application on a cloud service instance (web role) in Azure (Windows Server 2012 R2) with Magick.NET 7.0.1.101 (AnyCPU).
Magick.NET was unable to write the dll Magick.NET-Q16-x64.dll into the "Magick.NET.net40-client.7.0.1.101" directory because it throwed a System.UnauthorizedAccessException.
When checking the permissions, Read and Execute rights were granted for Everyone on the "Magick.NET.net40-client.7.0.1.101" directory and nothing else.
Do you need the Magick.NET.AnyCPU.NativeLibraryLoader.cs/GrantEveryoneReadAndExecuteAccess() method ? It seems the CreateDirectory() method automatically inherits permissions from the parent directory.
Or could you use this kind of logic, instead of granting rights for everyone ? http://stackoverflow.com/a/3626554
DirectoryInfo dInfo = new DirectoryInfo(strFullPath);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
//check off & copy inherited security setting
dSecurity.SetAccessRuleProtection(true, true);
dInfo.SetAccessControl(dSecurity);
I tried to use the Composite method with the following arguments :
public void Composite(MagickImage image, MagickGeometry offset, CompositeOperator compose)
{
Composite(image, offset, compose, null); //Call to the below method with a null args parameter
}
Infortunately, it throws a ArgumentNullException because it passes a null argument:
public void Composite(MagickImage image, MagickGeometry offset, CompositeOperator compose, string args)
{
Throw.IfNull("image", image);
Throw.IfNull("offset", offset);
_NativeInstance.SetArtifact("compose:args", args); // Throws ArgumentNullException if args is null
_NativeInstance.CompositeGeometry(image, MagickGeometry.ToString(offset), compose);
}
My simplified code goes like this:
var imageData = File.ReadAllBytes(@"ffed5e2f-359c-481f-b236-281360a91df7.JPG");
using (MagickImage image = new MagickImage())
{
image.Read(imageData);
var density = image.Density; //throws System.OverflowException - Arithmetic operation resulted in an overflow.
}
Sample file can be downloaded from https://cadworxshared.blob.core.windows.net/magicknet/ffed5e2f-359c-481f-b236-281360a91df7.JPG
Please note that this happens when using x64 with both Magick.NET-Q16-HDRI-AnyCPU and Magick.NET-Q16-HDRI-x64. It seems to work correctly in x86 but I need to use x64.
Thanks in advance.
hey,I use the Magick.NET 7.0.0.0021,it is working good in window7 32bit but when i put it in windows
2012R2 ,it can not load the file 'Magick.NET.Wrapper-x64.DLL'. I have install theVisual C++ Redistributable for Visual Studio 2015, and I also write the MagickAnyCPU.CacheDirectory, it make the file success but ,it still show this error.
The command line of ImageMagick is able to create lossless WebP images:
http://www.imagemagick.org/script/webp.php
Is it possible to achieve somehow through Magick.NET API?
Thanks!
The ToByteArray and ToShortArray methods of PixelCollection now expect a string for the mapping. An overload should be added that uses an enumeration instead. Due to the big number of options that mapping supports it might be better to limit the number of options in the enumeration to the most common ones (e.g. RGBA/ABGR/CMYK/etc.).
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.