It seems that .NET can't open JP2 (Jpeg 2000) files using the GDI library. I've searched on google but can't find any libraries or example code to do this.
Anybody got any ideas? I don't really want to pay for a library to do it unless I have to..
Seems like we can do it using FreeImage (which is free)
FIBITMAP dib = FreeImage.LoadEx("test.jp2");
//save the image out to disk
FreeImage.Save(FREE_IMAGE_FORMAT.FIF_JPEG, dib, "test.jpg", FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYNORMAL);
//or even turn it into a normal Bitmap for later use
Bitmap bitmap = FreeImage.GetBitmap(dib);
I was looking for something similar a while back, with a view to implementing one if I could; The responses to my question imply that there is no documented method to do this for GDI+ which the Image class in .Net uses.
I believe that if you're writing a WPF application, then you can extend the list of supported image formats through Windows Imanging Components codecs, and there may be one out there already (ask your local friendly search engine?)
There is an option to use an addon such as DotImage which supports JPEG2000, although there may be more "effort" involved in loading images.
For anyone coming across this old post, the above code from Gordon works great, but as jixtra pointed out, you will indeed get an exception: System.DllNotFoundException: 'Unable to load DLL 'FreeImage': The specified module could not be found.' when installing via nuget. I was able to get it working in .net 4.6.1 by installing the FreeImage-dotnet-core nuget package and manually adding the FreeImage.dll to the bin folder. You can download the dll here: http://freeimage.sourceforge.net/download.html.
I needed a better quality image to use with tesseract so I made a few minor changes which made a huge difference to the quality of the new jpeg:
var jp2Format = FREE_IMAGE_FORMAT.FIF_JP2;
var dib = FreeImage.LoadEx("test.jp2", ref jp2Format);
FreeImage.SetResolutionX(dib, 300);
FreeImage.SetResolutionY(dib, 300);
FreeImage.Save(FREE_IMAGE_FORMAT.FIF_JPEG, dib, "test.jpg", FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYSUPERB);
// NOTE: memory needs to be explicitly freed (GC won't do this)
FreeImage.UnloadEx(ref dib);
I've used Leadtools to display JPEG 2000 images. They provide a .NET library including WPF and WinForms controls to display the images. However, there is a reasonably steep price tag.
You can use Jpeg2000.Net library if you need a fully managed solution without unsafe blocks. Disclaimer: I am working on this library, the library is commercial.
Here is the basic sample for decoding of JPEG 2000 image to TIFF:
string fileName = ...; // path to JPEG 2000 image
using (var image = new J2kImage(fileName))
{
var options = new J2kDecodingOptions
{
UpsampleComponents = true
};
// Alternatively, you can decode only part of the image using J2kImage.DecodeArea method
var imageData = image.Decode(options);
imageData.Save(tiffFileName, J2kOutputFormat.Tiff);
}
Also, for a currently-up-to-date, open-source option you can use Emgu CV, which is a wrapper around OpenCV. Basic example code in C# looks like:
Mat image = CvInvoke.Imread(#"\Path\To\File.jp2");
Related
I'm try to create a simple WinForms viewer to show DICOM files generated in a NOVARAD PACS system. I'm using the following code from their GitHub page:
var image = new DicomImage(#"C:\myDicom.dcm");
image.RenderImage().AsClonedBitmap().Save(#"test.jpg");
Process.Start("test.jpg");
When I run this code I get the following error:
Dicom.Imaging.Codec.DicomCodecException: 'Decoding dataset with
transfer syntax: JPEG 2000 Image Compression (Lossless Only) is not
supported.'
I'm assuming I need to decompress from the JPEG 2000. Can this not be done with fo-dicom?
I was trying to play around with GDCM library but I couldn't find the C# wrapper, and noticed several comments saying they rolled it into fo-dicom.
Any suggestions?
In .NET Framework applications, the build architecture needs to be set to x86 or x64. Codec access on Any CPU architecture will not work, since there are no native codec libraries available for that architecture. For more information, see the fo-dicom wiki.
We have legacy applications built using VB6. These applications are using lead-tools. Everything was perfectly working. We have another .NET process that optimizes the image (and do some water-marking) and save it in tiff format. Here is glimpse of .NET code,
using (var bitmap = new Bitmap(contractWidth, contractHeight))
{
using (var canvas = Graphics.FromImage(bitmap))
{
canvas.InterpolationMode = InterpolationMode.Default;
// Play with canvas
canvas.Save();
}
using (var stream = new MemoryStream())
{
bitmap.Save(stream, ImageFormat.Tiff);
return stream.ToArray();
}
}
When we save this in tiff format (say image.tif). But when we open this file on our VB6 project, it shows a blue screen. I tried to compare the image which is working and image which is not working. Here are screens,
Working:
Not Working:
Update: This fixed my issue Convert TIFF to 1bit
I know you found a solution to the problem by converting the input image to 1-bit, but I wanted to elaborate more on the cause of the original problem, which is LEADTOOLS not opening the 32-bit file correctly in the first place.
You haven't specified which version of LEADTOOLS you're using, but since it's a legacy VB6 application, it's probably a rather old version (somewhere between v10 and v17; the current version is 20).
In any case, even older versions of the SDK should have no problem opening 32-bit TIFF files, but your application might be missing one or both of the following requirements:
Different sub-types of TIFF files require different LEADTOOLS DLLs. This is explained in the help topic Files to be Included with Your Application.
Older versions of the SDK required a special license to support LZW compression, back in the days when there was an active patent on LZW. If you're using one of these versions AND your application does not have that license, it won't support LZW tiff or gif files.
Please note that even owners of older SDK versions get free support. So if you are the owner of the original SDK, feel free to email any questions to support#leadtools.com, along with your LEADTOOLS product serial number.
I've got some C# code in Unity that grabs a large image from my Android Device's filesystem, and now with it I want to use it to create a small thumbnail image.
I've found lots of different suggestions for how to do this such as the following:
MemoryStream outputStream = new MemoryStream();
System.Drawing.Image image = System.Drawing.Image.FromFile(originalImagePath);
System.Drawing.Image thumbnail = image.GetThumbnailImage(thumbnailWidth, thumbnailHeight,()=>false, IntPtr.Zero);
thumbnail.Save(outputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
return outputStream;
However, as with the above method, all of the methods I've found require you to use the System.Drawing namespace. And I can't for the life of me get the functions in this namespace to work on Android, because even after adding "System.Drawing.dll" into the Assets folder, I get an error saying that it can't locate "gdiplus.dll" on construction of "System.Drawing.Image". I tried downloading and adding said "gdiplus.dll" to Assets, but I just get the same error as if it can't find it!
I don't understand why its so hard to get the System.Drawing functions working in Unity, but that's somewhat besides the point, as all I really want to do is create a thumbnail of an image that lives on the user's Android Device. Any suggestions would be welcome!
EDIT: I forgot to mention that I'd like to avoid solutions that use Texture2D's because they can't be run off the main thread, and hence come with performance consequences =(
Thanks in advance! =)
Don't use Texture2D.Resize, because the resulting texture will become grey:
After resizing, texture pixels will be undefined.
See this post for other solutions.
Old answer
I recommend use an opensource C# image processing library, such as ImageSharp or search it on GitHub.
The last solution is to write one yourself, if the performance or size of a 3rd-party library is still not good enough.
Here are two ideas I can come up with:
split the possibly lengthy reading and resizing procedure into several Coroutines.
use multi-thread
You may also try calling java functions from Unity3D. But I'm not familiar with that.
I get Out of Memory exception when using System.Drawing.Graphics.FromImage (using latest versions of .NET software on Windows 2012 server), ONLY on a very few specific image files. Most of the time the code works fine.
Typical answers to above issue indicate that certain resources are not being released.
Please consider the following before answering:-
This specific image is 34KB in size, is a .JPG image. Server is idle and has over 32GB RAM.
If I look at properties of
this jpg file, using windows explorer, by right-clicking on file, Windows says: 96 dpi and 32 bit depth.
BUT, if I open this jpg file using any graphics program (e.g. photoshop), the file properties show as: 72 dpi and 24 bit depth.
So, there is a mis-match between what I think file header properties
say and what the file actually contains.
Further, if I open the jpg
file using a graphics program and just re-save without changing
anything, the file properties in windows explorer now match/read correct
(72 dpi and 24 bit depth); and the file is processed by
System.Drawing.Graphics correctly, without throwing exception.
Due to my limited knowledge of the subject, I don't know if the file header of an image file can contain different data from actual file contents.
Questions:
How can I fix this problem? Or how can I tell System.Drawing.Graphics to ignore file header data and just look at actual image file contents? (as all graphics programs such as photoshop appear to do).
Thanks!
While I'm not a guru on the JPEG file format i did some research on the subject and here's what i found that could help you with your problem/questions.
Note that this answer will assume rather than specifically pinpoint the source of your problem due to the lack of an example file to inspect and tell what differs it from what the .Net/GDI+ JPEG/JFIF decoder expects.
The JPEG/JFIF format
Starting off, you might want to have some insight into the JPEG/JFIF format itself. After all, you have just encountered a file that .Net/GDI+ cannot load/parse. Since i don't have the file you experience issues with i would suggest you load it up in a hex editor of choice... that has the capability to highlight the file based on a template/code/parser.
I used 010 Editor and the JPEG Template from Sweetscape's online template repository.
010 Editor comes with a 30-day free trial.
What you are specifically looking for is the SOFn identifier and data in your bad JPEG.
In the SOFn data i can see that my image is Y (154) pixels high and X (640) pixels wide with a precision of 8 bits per component using 3 components, making it 24 bits per pixel.
The JPEG/JFIF format is a huge mix of many different implementations/formats. Obviously, you won't find every variant of the format in any library that has been around since long long ago before the odd JPEG formats appeared. Which the GDI+ library has.
In your case, i suspect you have run into the commonly asked about CMYK color profile on your JPEG files.
The .Net implementation
You said you used System.Drawing.Graphics.FromImage so i will assume your code looks like one of the following:
Graphics.FromImage(Image.FromFile("nope.jpg"));
Graphics.FromImage(Image.FromFile("nope.jpg", true));
Graphics.FromImage(Image.FromStream(nopeJpegStream));
From those calls, you may get an OutOfMemoryException when the native gdiplus.dll calls...
GdipGetImageGraphicsContext
GdipLoadImageFromFile
GdipLoadImageFromFileICM (or their respective *Stream variants) or
GdipImageForceValidation
... returns code 3 or 5 (Out of memory or Insufficient buffer respectively)
Which i gathered from referencesource.microsoft.com looking through the .Net sources there.
In any case, this most likely isn't an issue with .Net but an issue with GDI+ (gdiplus.dll) which Microsoft doesn't provide source code for. Which also means that there is no way of controlling how the image loads using the .Net wrappers and there's no way to check WHY it fails. (though i still suspect your JPEG is saved with CMYK)
Unfortunately, you are going to find many many more of these strange exceptions/errors as you move along in GDI+ land. As the library is all but deprecated in favor of the Windows Presentation Framework (WPF) and the Windows Imaging Component. (WIC)
My own testing
Since you never provided an image or any additional details on the subject i attempted to reproduce your issue. Which was a task in of itself, Image.FromFile (GdipLoadImageFromFile) will fail on many different file formats. At least it doesn't care what the file extension is, which thankfully Photoshop does.
So with your information, i finally managed to reproduce a .jpg file that loads fine in Photoshop, shows DPI as 96 and bit depth as 32. Of course, if i knew more about the JPEG format i probably could have gotten to the solution right away.
Showing this file (which i had to set to CMYK color space in Photoshop) in 010 Editor gave me the following SOFn data: Y (154) pixels high and X (640) pixels wide with a precision of 8 bits per component using 4 components, making it 32 bits per pixel.
I suspect you would see the same on your "bad" file.
And yes, Image.FromFile now throws an OutOfMemoryException!
Possible solutions
Use an external library for loading image files. (An exercise i leave to you but ImageMagick A.K.A Magick.NET seems like a good bet)
Make use of a command line tool (invoked when you get this exception) that can convert an image from one format to another. Or from JPEG to JPEG as it may be in this case. (Once again, ImageMagick's "convert" command line tool seems like a good bet)
Use the Windows Presentation Framework assemblies...
public static Image ImageFromFileWpf(string filename) {
/* Load the image into an encoder using the Presentation Framework.
* This is done by adding a frame (which in laymans terms is a layer) to a class derived BitmapEncoder.
* Only TIFF, Gif and JPEG XR supports multiple frames.
* Since we are going to convert our image to a GDI+ resource we won't support this as GDI+ doesn't (really) support it either.
* If you want/need support for layers/animated Gif files, create a similar method to this one that takes a BitmapFrame as an argument and then...
* 1. Instanciate the appropriate BitmapDecoder.
* 2. Iterate over the BitmapDecoders frames, feeding them to the new method.
* 3. Store the returned images in a collection of images.
*
* Finally, i opted to use a PngBitmapEncoder here which supports image transparency.
*/
var bitmapEncoder = new PngBitmapEncoder();
bitmapEncoder.Frames.Add(BitmapFrame.Create(new Uri(filename)));
// Use a memorystream as a handover from one file format to another.
using (var memoryStream = new MemoryStream()) {
bitmapEncoder.Save(memoryStream);
/* We MUST create a copy of our image from stream, MSDN specifically states that the stream must remain
* open throughout the lifetime of the image.
* We cannot instanciate the Image class, so we instanciate a Bitmap from our temporary image instead.
* Bitmaps are derived from Image anyways, so this is perfectly fine.
*/
var tempImage = Image.FromStream(memoryStream);
return new Bitmap(tempImage);
}
}
Based on this answer...
... Which i would say is a good option as it keeps you within the .Net framework.
Please keep in mind that when the method returns, you do specifically get a PNG image back. If you call Image.Save(string) on it you WILL save a PNG file, no matter what extension you save it as.
There is an overload Image.Save(string, ImageFormat) that will save the file using the intended file format. However, using that overload with ImageFormat.Jpeg will cause a loss in quality in the resulting file on more than one level.
That can be somewhat remedied by using the third overload:
foreach (var encoder in ImageCodecInfo.GetImageEncoders()) {
if (encoder.MimeType == "image/jpeg")
image.Save(filename, encoder, new EncoderParameters { Param = new [] { new EncoderParameter(Encoder.Quality, 100L) }});
}
Which, at least, will save a JPEG with "almost" no compression. GDI+ still doesn't do a good job at it.
However, no matter how much you twist and turn it. GDI+ will not be as good as a proper image library, which once again would most likely be ImageMagick. The further away you can get from GDI+, the better off you will be.
Conclusion / TL:DR and other notes.
Q: Can i load these files in .Net?
A: Yes, with a bit of fiddling and not using GDI+ for the initial loading of the file as GDI+ doesn't support the CMYK color space in JPEG files.
And even so, GDI+ lacks support for many things which is why i would recommend an external image library over GDI+.
Q: Mismatch in DPI and bit depth for file between Windows and <insert photo app here>
A: This is just proof that Windows JPEG loading differs from other applications JPEG loading routines. Only applications that use GDI or GDI+ would see the same information that Windows does when showing image details.
If you are using Windows 7+ then it isn't using GDI+ to show the information nor the image. It is using WPF or WIC to do so which are somewhat more up to date.
Q: If I open the jpg file using a graphics program and just re-save without changing anything, the file properties in windows explorer now match/read correct (72 dpi and 24 bit depth)
A: If you are using Adobe Photoshop and you use "Save for web" then the JPEG image will not be saved in CMYK format. Use "Save As..." instead and you will find that the color space (and bit depth) stays the same.
However, i wasn't able to reproduce your discrepancy in DPI and bit depth when loading my file in Photoshop. They are reported as the same in both Windows and Photoshop.
I had the same issue with this bug - seems as though the Graphics / Bitmap / Image library throws an exception with certain malformed images. Narrowing it down more than that, as Cadde shows, is difficult.
Following on from the great answer made by Cadde (which left using an external library as an exercise to the reader), I changed my code to the following using MagickNet which you can get here, or simply with NuGet: PM> Install-Package Magick.NET-Q16-x86.
The code tries to create a Graphics object from the image, and if it fails, uses ImageMagick to load the image again, convert to a Bitmap, and attempts to load from there.
Image bitmap = Bitmap.FromFile(filename, false);
Graphics graphics = null;
try
{
graphics = Graphics.FromImage(bitmap);
}
catch (OutOfMemoryException oome)
{
// Well, this looks like a buggy image.
// Try using alternate method
ImageMagick.MagickImage image = new ImageMagick.MagickImage(filename);
image.Resize(image.Width, image.Height);
image.Quality = 90;
image.CompressionMethod = ImageMagick.CompressionMethod.JPEG;
graphics = Graphics.FromImage(image.ToBitmap());
}
I had the same problem. My jpg file was generated from Photoshop. A simple solution is to open the jpg file with Winodws Paint, and save as a new jpg file. Import the new jpg file to C# project and the problem will be disappear.
i am currently exploring on how to create thumbnail from video file. so far, i am able to generate thumbnail using ffmpeg but can somebody suggest me if there any other ways to generate thumbnail without involving executable(.exe) file.
Thanks,
New Learner, Please guide me...
ffmpeg.exe is the best solution for Video Thumbnails generation as it is free software licensed under the LGPL or GPL.
There are few other places where you will find the solution:
C# Wrapper for the AviFile Library
DirectShow .NET
SlimDX is a free open source framework that enables developers to easily build DirectX applications using .NET technologies such as C#
If you just need a generic thumbnail an easy way to get one is through the WindowsAPICodePack.Shell package. A small, medium, large, or extra large thumbnail can be generated. There's not as much control over the output as ffmpeg but it's hard to beat this method when a generic thumbnail will do or when avoiding an outside exe.
using Microsoft.WindowsAPICodePack.Shell;
using System.Drawing;
namespace GetVideoThumbnail
{
class VideoThumbnail
{
static void Main(string[] args)
{
string videoPath = #"C:\Users\NotSure\Desktop\SampleVideo.MP4";
// Create shell object
ShellObject videoShellObject = ShellObject.FromParsingName(videoPath);
// Create bitmap and/or save locally
Bitmap thumbnailBmp = videoShellObject.Thumbnail.LargeBitmap;
thumbnailBmp.Save(#"C:\Users\NotSure\Desktop\SampleVideoThumbnail.bmp");
}
}
}
Yea!,good this interestingly Q.
I worked it issue,my diploma tasking-at Uni.
And more yet Articles.
1.OpenCV - This Open source project Best worked C/C++,C# and Java
2.Emg CV - This good worked C#
, and more...
Try it's open sources.
You may want to try the VideoFileReader from AForge, specifically AForge.Video.FFMPEG.VideoFileReader. It makes use of ffmpeg DLLs.
Alternatively, on Windows 7, you could use ShellFile.Thumbnail from WindowsAPICodePack or use DirectShow to save a frame with VideoRenderer.
I recently used the ShellFile method, with VideoFileReader as backup.