bitmiracle / libtiff.net Goto Github PK
View Code? Open in Web Editor NEW.NET version of LibTiff library made by Bit Miracle and contributors
Home Page: http://bitmiracle.com/libtiff/
License: Other
.NET version of LibTiff library made by Bit Miracle and contributors
Home Page: http://bitmiracle.com/libtiff/
License: Other
Hi there.
I have a system which needs to reduce the file size of TIFF images to 200KB at most, and I stumbled upon libtiff.net while searching for a solution.
Could someone please give an example of how to compress a picture using libtiff.net in C#? Thanks.
There are two problems that cause the issue:
When attempting to read the values for the X or YRESOLUTION tag in BigTIFF format images (this technique works for regular TIFF), we get nonsense values. The below code shows how it is currently being pulled.
FieldValue[] xResField = tiffHandle.GetField(TiffTag.XRESOLUTION);
float pixelsPerUnitX = xResField[0].ToFloat();
var stream = new MemoryStream(File.ReadAllBytes(@"D:\1.tif"));
using (Tiff input = Tiff.ClientOpen("in-memory", "a", stream, new TiffStream()))
{
input.SetDirectory(0);
var result=input.SetField(TiffTag.ORIENTATION, BitMiracle.LibTiff.Classic.Orientation.RIGHTBOT);
input.CheckpointDirectory();
input.Close();
}
no working !!!
result is true but no change the orientation in the tiff
Hi,
I tried to use LibTIFF under Linux and OSX. The NuGet packet installs fine, but in both cases I get the exact same error message:
Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'BitMiracle.LibTiff.NetStandard, Version=2.4.583.0, Culture=neutral, PublicKeyToken=53879b3e20e7a7d6'. The system cannot find the file specified.
I compiled recent libtiff.net40 project (2.4.583.0) and tiffcp with Visual Studio 2017 using .net 4.7 framework and execute tiffcp.
C:\libtiff\libtiff.net\TiffCP\bin\Release>TiffCP.exe C:/tmp/logo1.tif C:/tmp/logo2.tif
C:/tmp/logo2.tif: Warning, "WhitePoint": Information lost writing value (-1.343036E+09) as (unsigned) RATIONAL
C:/tmp/logo2.tif: Warning, "WhitePoint": Information lost writing value (-1.413044E+09) as (unsigned) RATIONAL
C:/tmp/logo2.tif: Warning, "PrimaryChromaticities": Information lost writing value (-1.417339E+09) as (unsigned) RATIONAL
C:/tmp/logo2.tif: Warning, "PrimaryChromaticities": Information lost writing value (-1.28849E+09) as (unsigned) RATIONAL
C:/tmp/logo2.tif: Warning, "PrimaryChromaticities": Information lost writing value (-6.442451E+08) as (unsigned) RATIONAL
C:/tmp/logo2.tif: Warning, "PrimaryChromaticities": Information lost writing value (-2.57698E+08) as (unsigned) RATIONAL
I checked it with tiffinfo/tiffdump come with libtiff 4.0.7 on cygwin.
$ tiffinfo logo1.tif
TIFF Directory at offset 0x6e04 (28164)
Image Width: 640 Image Length: 480
Bits/Sample: 8
Compression Scheme: LZW
Photometric Interpretation: palette color (RGB from colormap)
FillOrder: msb-to-lsb
Orientation: row 0 top, col 0 lhs
Samples/Pixel: 1
Rows/Strip: 480
Planar Configuration: single image plane
Page Number: 0-1
Color Map: (present)
White Point: 0.3127-0.329
PrimaryChromaticities: 0.640000,0.330000,0.300000,0.600000,0.150000,0.060000
$ tiffinfo logo2.tif
TIFF Directory at offset 0x6e0c (28172)
Image Width: 640 Image Length: 480
Bits/Sample: 8
Compression Scheme: LZW
Photometric Interpretation: palette color (RGB from colormap)
FillOrder: msb-to-lsb
Orientation: row 0 top, col 0 lhs
Samples/Pixel: 1
Rows/Strip: 480
Planar Configuration: single image plane
Page Number: 0-1
Color Map: (present)
White Point: 0-0
PrimaryChromaticities: 1546188288.000000,0.000000,0.000000,1717986816.000000,0.000000,0.000000
And tried to copy the same input file with original tiffcp come with libtiff 4.0.7
$ tiffcp logo1.tif logo3.tif
$ tiffinfo logo3.tif
TIFF Directory at offset 0x6e04 (28164)
Image Width: 640 Image Length: 480
Bits/Sample: 8
Compression Scheme: LZW
Photometric Interpretation: palette color (RGB from colormap)
FillOrder: msb-to-lsb
Orientation: row 0 top, col 0 lhs
Samples/Pixel: 1
Rows/Strip: 480
Planar Configuration: single image plane
Page Number: 0-1
Color Map: (present)
White Point: 0.3127-0.329
PrimaryChromaticities: 0.640000,0.330000,0.300000,0.600000,0.150000,0.060000
So something is wrong with libtiff.NET version for RATIONAL tag.
PS: logo1.tif is created by ImageMagick 7.0.7-1 Q16 by using the followng command:
magick logo: logo1.tif
Hello,
I'm using your library to create enormous images. However when using the library to save an image of the following size I encounter some overflows when the directory is written to the file:
Width: 1048576
Height: 1048576
TileSize: 64x64
SizeOf(ulong): 8
In the WriteDirectory method (and submethods) a lot of BlockCopies are done (could probably also be optimized to reduce the memory footprint). BlockCopies work on byte level though so this means that when we have a total number of tiles of: (1048576 / 64) * (1048576 / 64) = 268435456. And we then multiply this number by the size of ulong to get the total amount of bytes we get a total of 2147483648 bytes. This happens to be just over int.MaxValue which results in the following exception being thrown:
30-10-2015 05:30:17: System.ArgumentOutOfRangeException: Non-negative number required.
Parameter name: count
at System.Buffer.BlockCopy(Array src, Int32 srcOffset, Array dst, Int32 dstOffset, Int32 count)
at BitMiracle.LibTiff.Classic.Tiff.writeDirectory(Boolean done) in D:\The folder\Github\DeveMazeGenerator\LibTiff\LibTiff\Internal\Tiff_DirWrite.cs:line 206
at BitMiracle.LibTiff.Classic.Tiff.Flush() in D:\The folder\Github\DeveMazeGenerator\LibTiff\LibTiff\Tiff.cs:line 767
at BitMiracle.LibTiff.Classic.Tiff.Close() in D:\The folder\Github\DeveMazeGenerator\LibTiff\LibTiff\Tiff.cs:line 495
at BitMiracle.LibTiff.Classic.Tiff.Dispose(Boolean disposing) in D:\The folder\Github\DeveMazeGenerator\LibTiff\LibTiff\Internal\Tiff_Internal.cs:line 326
at BitMiracle.LibTiff.Classic.Tiff.Dispose() in D:\The folder\Github\DeveMazeGenerator\LibTiff\LibTiff\Tiff.cs:line 514
at DeveMazeGenerator.Maze.Testje(Int32 size, Action2 lineSavingProgress, Int32 tiffTileSize, Boolean useComplexImage, Action
1 debugMessageCallback) in D:\The folder\Github\DeveMazeGenerator\DeveMazeGenerator\Maze.SavingDeluxeTiff.cs:line 1016
at DeveMazeGeneratorGui.Form1.<>c__DisplayClass75_0.<button45_Click>b__0() in D:\The folder\Github\DeveMazeGenerator\DeveMazeGeneratorGui\Form1.cs:line 2235
Is this something that can be resolved? (e.g. by replacing the BlockCopies by something that will keep processing them as long arrays and somehow write that to the file directly). Or maybe even writing the directory directly after writing the tile? (To also save memory on storing all locations of tiles).
Thanks all for the amazing work :),
Devedse
When I add just one file to the tiff then everything works fine. But when I try to add 2 or more files then the tiff gets corrupted. Can somebody tell me what I'm doing wrong?
private static byte[] GetImageRasterBytes(Bitmap bmp, PixelFormat format)
{
var rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
byte[] bits;
try
{
// Lock the managed memory
var bmpdata = bmp.LockBits(rect, ImageLockMode.ReadWrite, format);
// Declare an array to hold the bytes of the bitmap.
bits = new byte[bmpdata.Stride * bmpdata.Height];
// Copy the values into the array.
System.Runtime.InteropServices.Marshal.Copy(bmpdata.Scan0, bits, 0, bits.Length);
// Release managed memory
bmp.UnlockBits(bmpdata);
}
catch
{
return null;
}
return bits;
}
/// <summary>
/// Converts BGR samples into RGB samples
/// </summary>
private static void ConvertRgbSamples(IList<byte> data, int width, int height)
{
var stride = data.Count / height;
const int samplesPerPixel = 3;
for (var y = 0; y < height; y++)
{
var offset = stride * y;
var strideEnd = offset + width * samplesPerPixel;
for (var i = offset; i < strideEnd; i += samplesPerPixel)
{
var temp = data[i + 2];
data[i + 2] = data[i];
data[i] = temp;
}
}
}
private void button1_Click(object sender, EventArgs e)
{
var outputFile = @"d:\test.tif";
var inputFiles = new List<string>();
inputFiles.Add("d:\\Screenshot_20190624-140341_Word.jpg");
//inputFiles.Add("d:\\Screenshot_20190624-214548_Gallery.jpg");
using (var output = Tiff.Open(outputFile, "w"))
{
var page = 0;
var pages = inputFiles.Count;
foreach (var inputFile in inputFiles)
{
page += 1;
using (var bitmap = (Bitmap) Image.FromFile(inputFile))
{
output.SetField(TiffTag.IMAGEWIDTH, bitmap.Width);
output.SetField(TiffTag.IMAGELENGTH, bitmap.Height);
output.SetField(TiffTag.BITSPERSAMPLE, 8);
output.SetField(TiffTag.ORIENTATION, Orientation.TOPLEFT);
output.SetField(TiffTag.SAMPLESPERPIXEL, 3);
output.SetField(TiffTag.ROWSPERSTRIP, bitmap.Height);
output.SetField(TiffTag.COMPRESSION, Compression.JPEG);
output.SetField(TiffTag.PHOTOMETRIC, Photometric.RGB);
//output.SetField(TiffTag.FILLORDER, FillOrder.MSB2LSB);
output.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG);
output.SetField(TiffTag.SUBFILETYPE, FileType.PAGE);
output.SetField(TiffTag.PAGENUMBER, page, pages);
var bytes = GetImageRasterBytes(bitmap, PixelFormat.Format24bppRgb);
var stride = bytes.Length / bitmap.Height;
ConvertRgbSamples(bytes, bitmap.Width, bitmap.Height);
for (int i = 0, offset = 0; i < bitmap.Height; i++)
{
output.WriteScanline(bytes, offset, i, 0);
offset += stride;
}
}
}
}
I have a very large TIFF of size 19592*40325 pixels.
And when I create a new array for it, I immediately get System.OutOfMemoryException.
int imageSize = width * height;
int[] raster = new int[imageSize];
input.ReadRGBAImageOriented(width, height, raster, BitMiracle.LibTiff.Classic.Orientation.TOPLEFT);
So, is there any other way to get the raster as a Bitmap without converting it to RGBA first?
According to https://bitmiracle.github.io/libtiff.net/html/e00d6851-cf09-287f-638b-fc62c498351a.htm,
Options for CCITT Group 3/4 fax encoding.
Possible values for TiffTag.GROUP3OPTIONS / TiffTag.T4OPTIONS and TiffTag.GROUP4OPTIONS / TiffTag.T6OPTIONS tags.
However the code does not support this. Can it be added?
Additional information here: http://stackoverflow.com/questions/30630764/libtiff-net-group3opt-fillbits-is-not-filling-to-byte-boundary
Thank you.
-Mike
When I'm trying to open a TIF image with LZW compression having a bit depth of 4 bitspersample, I get the error "Sorry, can not handle image".
I can see that the method pickContigCase(), when handling bitmaps based on LZW-compression and RGB photometric, only take into account situations in which the bitspersample value is either 8 or 16
(it happens here).
What if the bitspersample is 4?
Hi all,
I need to understand if that error is something related the libtiff or not.
When I call: tiff.ReadScanline(sourceBuffer[i], (int)i), with "i" like an iterator of the Image Width, I have that error:
Non-negative number required
Parameter name: srcOffset
And the stack trace is:
System.Buffer.BlockCopy(Array src, Int32 srcOffset, Array dst, Int32 dstOffset, Int32 count)
in BitMiracle.LibTiff.Classic.Internal.DumpModeCodec.DumpModeDecode(Byte[] buffer, Int32 offset, Int32 count, Int16 plane)
in BitMiracle.LibTiff.Classic.Tiff.ReadScanline(Byte[] buffer, Int32 offset, Int32 row, Int16 plane)
in BitMiracle.LibTiff.Classic.Tiff.ReadScanline(Byte[] buffer, Int32 row)
Someone can explane me how I can avoid at that problem? I don't set a srcOffset on my call.
Thank you
Daniel
I'm working on my own code. I was examining how you swap bytes using your Swab functions, particularly the SwabShort.
https://github.com/BitMiracle/libtiff.net/blob/master/LibTiff/Tiff.cs#L5681
There's one issue I'm not sure your code takes into account (I haven't thoroughly looked). Your SwabShort accepts signed values, limiting it to max positive of 0x7FFF. What happens when you try to get a tag value of 0x8769 (Exif IFD)? That won't fit, so the value ends up overflowing, and you get a non-existent tag name.
If you have taken care of this issue, let me know how. Otherwise, all I did was change the shorts to ushorts.
Is there a way to open Tiff
instances that are backed by streamed content that are not files?
I was looking for a Tiff to Pdf converter that could be used in an Asp.Net web service to stream in Tiff files from another service, convert the content, and stream out Pdf content in a response, without having to touch the file system.
I was able to hack a couple of new methods into Tiff
and ExtenderAndErrorHandler
to allow me to basically hand my own input stream into ClientOpen
, and then use the T2P
class as-is to convert the Tiff in-memory and stream out the result.
But maybe I'm missing something obvious and this use case is already supported?
hey there im write a program for a conversion of an generic .raw to .dng and it works fine exept those two tifftags:
private const long white = 3576, black = 512;
.
.
tif.SetField(TiffTag.WHITELEVEL, 1, white);
tif.SetField(TiffTag.BLACKLEVEL, 1, black);
.
when i debug this exeption is thrown:
A first chance exception of type 'System.NullReferenceException' occurred in BitMiracle.LibTiff.NET.dll
Additional information: Object reference not set to an instance of an object.
If there is a handler for this exception, the program may be safely continued.
i used the precompiled dll and compiled it on my own im using vs studio 2013 express desktop
call stacks:
in tiff.cs line 2885 return m_tagmethods.SetField(this, tag, FieldValue.FromParams(value));
and then the final break in
TiffTagMethods.cs lin 499 Buffer.BlockCopy(apBytes, 0, td.td_customValues[tvIndex].value, 0, Math.Min(apBytes.Length, td.td_customValues[tvIndex].value.Length));
hope anybody can help cause when i need white and black level :-) when i remove the two the conversion works fine.
thx janosch
Attached test.tiff is taken from ImageMagick forum https://imagemagick.org/discourse-server/viewtopic.php?p=171840&sid=d9679f9cf51a671c5ad80b78138cee9e#p171840
I tested it on current LibTiff.NET and got the error:
static void Main(string[] args)
{
using (Stream stream = new FileStream(args[0], FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (var inImage = Tiff.ClientOpen(string.Empty, "r", stream, new TiffStream()))
{
short totalPages = inImage.NumberOfDirectories();
for (short i = 0; i < totalPages; i++)
{
bool ret = inImage.SetDirectory(i);
Console.Out.WriteLine(string.Format("{0}: {1}", i, ret));
}
}
}
}
Result:
0: True
1: True
2: True
3: True
4: True
5: True
6: True
7: True
8: True
: Cannot handle different per-sample values for field "SMinSampleValue"
9: False
So I checked the code and tiff spec and found this error is checked at fetchPerSampleAnys() in Tiff_DirRead.cs.
According to libtiff mailing list, it is the limitation of libtiff:
https://www.asmail.be/msg0055373960.html
All the values have to be the same.
SMinSampleValue (340) FLOAT (11) 3<0.00610352 0.00720215 0.00146484>
SMaxSampleValue (341) FLOAT (11) 3<15.125 15.125 15.3125>
However it does not affect the image presentation.
https://www.awaresystems.be/imaging/tiff/tifftags/minsamplevalue.html
(Strictly, the description is for obsolete(?) MinSampleValue and not for SMinSampleValue, but I guess the meaning is the same.)
So I'd like to remove this tag first as a workaround.
Using libtiff command, it is easy:
% tiffset -d 9 -u 340 test.tiff
% tiffset -d 9 -u 341 test.tiff
Then the modified file becomes able to be handled with LibTiff.NET.
However, Id' like to accomplish this with LibTiff.NET if possible.
Even using TiffCP.exe compiled from your TiffCP project,
% libtiff.net-master/TiffCP/bin/Debug/TiffCP.exe test.tiff a.tif
test.tiff: Cannot handle different per-sample values for field "SMinSampleValue"
test.tiff,9 not found!
because it uses ReadDirectory() as well.
Note that original tiffcp comes with libtiff can copy this file and correct the value:
SMinSampleValue (340) FLOAT (11) 3<0.00146484 0.00146484 0.00146484>
SMaxSampleValue (341) FLOAT (11) 3<15.3125 15.3125 15.3125>
So, here is the question.
Is it necessary to check this value at ReadDirectory() ?
If so, how to remove problematic SMinSampleValue tag using LibTiff.NET?
Best Wishes,
test.zip
PS. This file can be opened with Gimp, Krita and Mac preview, but Windows Photo Viewer failed to read it.
Hi,
I'm new to tiff image processing and would like to split a single-page tiff raster (20000 * 20000) into 100 smaller tiff files (each of size 200 * 200) using libtiff.net
. Similar to as described in this article using Python (GDAL).
I've looked at the samples but couldn't find it.
Hello, I am working on a project which requires 32 bits per sample support. Is it possible to implement this? I am perfectly willing to put my own time towards this but I wanted to get a sense of the difficulty.
Its deprecated. yes but old applications and hardware required it to be in this format. its there any way to make it work with net.LibTIff?
This project is wonderful.
I have a 40bit depth TIF file which is using CMYKA.
The .Net Image.FromFile method will be throw out of memory exception when load it in. I think the .Net Image class don't support CMYKA image.
I tried this project, it can load it and convert it into PNG file. But the transparent background will turn to white.
I debug the project, I found the TiffRgbaImage.putRGBcontig8bitCMYKtitle method only treated the CMYK to RGB situation. Does this project plan to support CMYKA TIF?
By the way, when image is CMYKA the samplesperpixel is 5.
I made a clone from Github, opened LibTiff.NET_NoSilverlight.sln
, and tried to build the LibTiff project. The build fails because "AssemblyVersion.cs" is missing. Please add it to the repo so I can build after a fresh clone.
In TiffCp if certain errors occur (I'm copying a page which has a non standard JPEG compression - but it's not OJPEG :) ) then the directory is copied but the page data is not. This means you end up with a Tiff file where one page is not readable. If one page cannot be read would it better for TiffCP to fail?
I debugged this using my image. In Tiff.cs at line 5304 (in the function WriteEncodedStrip) the function EncodeStrip is failing so the function is returning 0. This means the directory gets written but not an image data. Would it be better to return -1 and abandon the copy? (or only return 0 if we are ignoring errors? - I can see several cases in Tiff.cs where an error is displayed but a function returns 0.)
Recently I was exploring the TiffTo32BitBitmap example on the site, and this worked well for a single directory. Interestingly, if one loops over all of the directories and exports the images sequentially, I am getting an out of memory exception when trying to allocate the raster array. This works for the first 6 directories, but runs out of memory on the 7th.
Below is the code I am using, which is a slight derivative of the example, and only loops over the directories to export the bitmaps.
Imports System.Drawing
Imports System.Drawing.Imaging
Imports BitMiracle.LibTiff.Classic
Module Module2
Public NotInheritable Class TiffTo32BitBitmaps
Public Sub New(FileName As String)
Using tif As Tiff = Tiff.Open(FileName, "r")
Dim directorycount As Integer = tif.NumberOfDirectories
For i As Integer = 0 To directorycount - 1
tif.SetDirectory(i)
' Find the width and height of the image
Dim value As FieldValue() = tif.GetField(TiffTag.IMAGEWIDTH)
Dim width As Integer = value(0).ToInt()
value = tif.GetField(TiffTag.IMAGELENGTH)
Dim height As Integer = value(0).ToInt()
' Read the image into the memory buffer
Dim raster As Integer() = New Integer(height * width - 1) {}
If Not tif.ReadRGBAImage(width, height, raster) Then
System.Windows.Forms.MessageBox.Show("Could not read image")
Return
End If
Using bmp As New Bitmap(width, height, PixelFormat.Format32bppRgb)
Dim rect As New Rectangle(0, 0, bmp.Width, bmp.Height)
Dim bmpdata As BitmapData = bmp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb)
Dim bits As Byte() = New Byte(bmpdata.Stride * bmpdata.Height - 1) {}
For y As Integer = 0 To bmp.Height - 1
Dim rasterOffset As Integer = y * bmp.Width
Dim bitsOffset As Integer = (bmp.Height - y - 1) * bmpdata.Stride
For x As Integer = 0 To bmp.Width - 1
Dim rgba As Integer = raster(rasterOffset)
rasterOffset = rasterOffset + 1
bits(bitsOffset) = CByte((rgba >> 16) And &HFF)
bits(bitsOffset + 1) = CByte((rgba >> 8) And &HFF)
bits(bitsOffset + 2) = CByte(rgba And &HFF)
bits(bitsOffset + 3) = CByte((rgba >> 24) And &HFF)
bitsOffset = bitsOffset + 4
Next
Next
System.Runtime.InteropServices.Marshal.Copy(bits, 0, bmpdata.Scan0, bits.Length)
bmp.UnlockBits(bmpdata)
Dim tFile As String = System.IO.Path.GetFileNameWithoutExtension(FileName)
Dim tDir As String = System.IO.Path.GetDirectoryName(FileName)
Dim tOutFileName As String = System.IO.Path.Combine(tDir, tFile & "_" & i & ".tif")
bmp.Save(tOutFileName)
'System.Diagnostics.Process.Start(tOutFileName)
Console.WriteLine("Exporting: " & tOutFileName)
End Using
tif.FreeDirectory()
Next
End Using
End Sub
End Class
End Module
Hi,
I tried to build the library, because the NuGet version of libtiff did not work with .NET Core. I got the following errors:
Build started 5/19/2017 3:51:46 PM.
__________________________________________________
Project "/Users/lennart/Downloads/libtiff.net-master/LibTiff.NET40/LibTiff.NET40.csproj" (build target(s)):
Target PreBuildEvent:
cd "/Users/lennart/Downloads/libtiff.net-master/"
update_version_info.bat "/Users/lennart/Downloads/libtiff.net-master/LibTiff.NET40/AssemblyVersion.cs"
/var/folders/_0/f4ghq9nj3_g5jgrmy683ttxm0000gp/T/tmpe104ea4c4e374a4d8c0ee8e8b6944698.exec.cmd: line 3: update_version_info.bat: command not found
/Library/Frameworks/Mono.framework/Versions/5.0.0/lib/mono/msbuild/15.0/bin/Microsoft.Common.CurrentVersion.targets(1279,5): error MSB3073: The command "cd "/Users/lennart/Downloads/libtiff.net-master/"
/Library/Frameworks/Mono.framework/Versions/5.0.0/lib/mono/msbuild/15.0/bin/Microsoft.Common.CurrentVersion.targets(1279,5): error MSB3073: update_version_info.bat "/Users/lennart/Downloads/libtiff.net-master/LibTiff.NET40/AssemblyVersion.cs"
/Library/Frameworks/Mono.framework/Versions/5.0.0/lib/mono/msbuild/15.0/bin/Microsoft.Common.CurrentVersion.targets(1279,5): error MSB3073: " exited with code 127.
Done building target "PreBuildEvent" in project "LibTiff.NET40.csproj" -- FAILED.
Done building project "LibTiff.NET40.csproj" -- FAILED.
__________________________________________________
Project "/Users/lennart/Downloads/libtiff.net-master/LibTiff.NetStandard/LibTiff.NetStandard.csproj" (build target(s)):
Target PreBuildEvent:
cd "/Users/lennart/Downloads/libtiff.net-master/"
update_version_info.bat "/Users/lennart/Downloads/libtiff.net-master/LibTiff.NetStandard/AssemblyVersion.cs"
/var/folders/_0/f4ghq9nj3_g5jgrmy683ttxm0000gp/T/tmpe8c6f446cebe464cb07d1a800c2dd895.exec.cmd: line 3: update_version_info.bat: command not found
/Library/Frameworks/Mono.framework/Versions/5.0.0/lib/mono/msbuild/15.0/bin/Microsoft.Common.CurrentVersion.targets(1279,5): error MSB3073: The command "cd "/Users/lennart/Downloads/libtiff.net-master/"
/Library/Frameworks/Mono.framework/Versions/5.0.0/lib/mono/msbuild/15.0/bin/Microsoft.Common.CurrentVersion.targets(1279,5): error MSB3073: update_version_info.bat "/Users/lennart/Downloads/libtiff.net-master/LibTiff.NetStandard/AssemblyVersion.cs"" exited with code 127.
Done building target "PreBuildEvent" in project "LibTiff.NetStandard.csproj" -- FAILED.
Done building project "LibTiff.NetStandard.csproj" -- FAILED.
__________________________________________________
Project "/Users/lennart/Downloads/libtiff.net-master/LibTiff/LibTiff.csproj" (build target(s)):
Target PreBuildEvent:
cd "/Users/lennart/Downloads/libtiff.net-master/"
update_version_info.bat "/Users/lennart/Downloads/libtiff.net-master/LibTiff/AssemblyVersion.cs"
/var/folders/_0/f4ghq9nj3_g5jgrmy683ttxm0000gp/T/tmp7cf2ee09bc3c4beeb9f5b28f322c619b.exec.cmd: line 3: update_version_info.bat: command not found
/Library/Frameworks/Mono.framework/Versions/5.0.0/lib/mono/msbuild/15.0/bin/Microsoft.Common.CurrentVersion.targets(1279,5): error MSB3073: The command "cd "/Users/lennart/Downloads/libtiff.net-master/"
/Library/Frameworks/Mono.framework/Versions/5.0.0/lib/mono/msbuild/15.0/bin/Microsoft.Common.CurrentVersion.targets(1279,5): error MSB3073: update_version_info.bat "/Users/lennart/Downloads/libtiff.net-master/LibTiff/AssemblyVersion.cs"
/Library/Frameworks/Mono.framework/Versions/5.0.0/lib/mono/msbuild/15.0/bin/Microsoft.Common.CurrentVersion.targets(1279,5): error MSB3073: " exited with code 127.
Done building target "PreBuildEvent" in project "LibTiff.csproj" -- FAILED.
Done building project "LibTiff.csproj" -- FAILED.
I am trying to set existing metadata tag to the existing Tiff image with 2 pages. eg: Author(ARTIST) tag (ItemID 315) using libTiff.Net.
using this link : http://bitmiracle.github.io/libtiff.net/html/f47d1201-0893-45dc-907e-2bbeb5e3cb0c.htm, I have changed tag id to 315 instead of 42112 and tried running code, The "Author" metadata is setting properly. But the output tiff first page has proper image and second page has black patch.
Please let me know is there any way to set the metadata especially for multipage Tiff file using libTiff.Net library.
Thanks in advance
I have recently been using your excelent library to merge some tiff files, but I've come across an issue.
The tiffs im getting from a 3rd party, is using the tag type SHORT for StripOffset (273) whenever the tiffs are below 64k in size.
This is producing overfow errors for all the offsets above 32k as you use short instead of ushort as the datatype.
Is there any reason for using the signed type ? Im assuming the offsets cant be negative.
Attached tiff is intentionally looped, i.e. next IFD of 2nd page is pointed to 1st page.
When I read this tiff and call NumberOfDirectories()
Stream stream = File.Open("../../logo2.tif", FileMode.Open, FileAccess.Read);
using (var inFile = Tiff.ClientOpen(string.Empty, "r", stream, new TiffStream()))
{
Console.Out.WriteLine(inFile.NumberOfDirectories());
}
program never returns.
IMHO, most tiff handling program first checks the number of page, so I think this should throw some exception to avoid DOS attack.
The error when opening the csproject file is
error : The default XML namespace of the project must be the MSBuild XML namespace. If the project is authored in the MSBuild 2003 format, please add xmlns="http://schemas.microsoft.com/developer/msbuild/2003" to the element. If the project has been authored in the old 1.0 or 1.2 format, please convert it to MSBuild 2003 format.
I'm using your library to create very large tiffs from stitched microscopy images. Your code has been working great! I really appreciate this project! I recently ran into a problem that I've been unable to figure out a solution for. When writing the output for one particularly large scan, I'm running into an Overflow Exception in MakeBigTiff.
For this problematic scan, the details are that I'm writing out a 81,920 x 57,344 tiled tiff. (16bit, single channel) I then create a second tiled tiff that's 40,960 x 28672. I open the larger tiff in "a" mode and add the second image as a page by copying one tile at a time. After all of the tiles have been copied, as the tiff objects are disposed, the exception occurs in the MakeBigTiff method. This code has been working fine now with many other smaller files.
I've stepped through the source code for MakeBigTiff a few times, but so far I'm unable to identify exactly what the issue is. I've had a tough time following the intended logic in this method. I see at least a couple of places where values appear to be read into variables that are too small to hold them. I'm unsure though if some of this is intentional.
I made one attempt at creating a unit test that could reproduce the issue. That first attempt didn't trigger the exception, but it did create a tiff file that couldn't be opened. I'm going to try another attempt using the same exact dimensions as the problematic image - I'll update this ticket with that test, if it works.
Here's the exception text:
System.OverflowException occurred
HResult=-2146233066
Message=Arithmetic operation resulted in an overflow.
Source=BitMiracle.LibTiff.NET40
StackTrace:
at BitMiracle.LibTiff.Classic.Tiff.MakeBigTIFF() in C:\Root\GitHub\Repos\libtiff.net\LibTiff\Internal\Tiff_DirWrite.cs:line 490
InnerException:
I Want to use this library to get all frames,like this
public List<Bitmap> GetAllTiffFrames(string tifPath)
{
}
if tif file have three frames,the function will return three bitmaps to list,but I do not know how to fill code to the function.
Trying to write a DNG using this library like in this example that was done in C++: https://lab.apertus.org/T759
I dunno how to do the CFARepeatPatternDim tag, as it doesn't seem to be implemented. Also, CFAPattern doesn't seem to exist, however EXIF_CFAPATTERN exists, is that the same thing?
And the photometric interpretation as CFA pattern and linear data doesn't seem to exist. I think I can just enter the correct number instead, but I'm not sure.
See page 20 of the DNG spec: https://www.adobe.com/content/dam/acom/en/products/photoshop/pdfs/dng_spec_1.4.0.0.pdf
Open a tiff stack with thousands of pages. Read page 3500 (in my testing it started failing on page 3495 but this may vary). System.IO.Exception thrown in ReadScanline. I tracked the problem down to Tiff_DirRead.cs:783 in fetchLong8Array. dir.tdir_offset is cast to (int) and should be (long).
hello.
is there a way to get the longitude and latitude off the tif file using libtiff.net?
thank you very much
Hi There
im using Unity 2019.2 and BitMiracle v2.4.6, i want to read 32-64 floating point Tiff files
so im using this code :
Hi!
Thank you for this great library, but I'm having some issues while loading the attached picture with the following code:
using (var image = Tiff.ClientOpen(null, "r", stream, new TiffStream()))
{
if (image == null)
{
throw new Exception("Invalid TIFF image");
}
var value = image.GetField(TiffTag.IMAGEWIDTH);
var width = value[0].ToInt();
value = image.GetField(TiffTag.IMAGELENGTH);
var height = value[0].ToInt();
value = image.GetField(TiffTag.ORIENTATION);
var orientation = (Orientation)value[0].ToInt();
imageData = new ImageData(width, height, new int[height * width]);
if (!image.ReadRGBAImageOriented(width, height, imageData.Data, orientation))
{
throw new Exception("Could not read TIFF image");
}
}
return imageData;
TIFF file:
kit.zip
Am I doing something wrong?
@Bobrovsky Could you please show (or add a sample) how a bitmap could be converted to 8-bit grayscale TIFF like the examples you have in VB.NET?
Many thanks!
Hi,
Does the library support OME-TIFF format? How do I read OME-TIFF comment? Is the following the right code to use?
string comment = "";
using (Tiff tif = Tiff.Open(file, "r"))
{
if (tif != null)
{
tif.SetDirectory(0);
FieldValue[] res = tif.GetField(TiffTag.IMAGEDESCRIPTION);
comment = (res == null ? "" : res[0].ToString());
}
}
}
My end goal is to convert OME-Tiff to normal TIFF. I can use ImageJ with Bioformats plugin to open OME-TIFF file and then save it as TIFF. Maybe, you have some gotchas for me.
Sample OME-TIFF file is attached.
B2-2-C1.zip
Thank you,
Victor.
There's code in the samples indicating that Tiff2Pdf is included as a library along with the other libraries. But I never could find it in the Object Browser of any of the .NET DLL's.
Here's the code in the documentation:
using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using BitMiracle.LibTiff.Classic;
namespace BitMiracle.LibTiff.Samples
{
public static class ConvertTiffToPdf
{
public static void Main()
{
string inputFile = @"Sample Data\multipage.tif";
string outputFile = "output.pdf";
string[] arguments = new string[] { "-o", outputFile, "-p", "A4", inputFile };
BitMiracle.Tiff2Pdf.Program.Main(arguments);
Process.Start(outputFile);
}
}
}
Wanted to let you know that the builds after 2.4.571 are causing unresolved references. It may be a versioning issue for I have .NET 4.6. Thanks.
Is it possible to load data from byte array (instead of file)? I am happy to contribute.
I see some code that is conditional upon THREAD_SAFE_LIBTIFF being set.
It appears that the library is not threadsafe unless this token is set, however the default project does not seem to set it.
If I am seeing things correctly, it seems like a better default would be that the library should be thread safe.
Currently, there is a 2.0 TargetFrameworkVersion build.
Would it be possible to add another one for 4.0 or 4.5?
If that fits your plans I could add a PR.
How is the offset-parameter used in TiffRgbaImage.GetRaster()?
I'm trying to read a small rectangle portion from a big tiff-image with GetRaster, but all I get is IndexOutOfRange-exception.
For example:
var rect= new Rectangle(100, 100, 200, 200);
var raster = new int[rect.Width * rect.Height];
var offset = image.Width * rect.Top + rect.Left;
_tiffRgba.GetRaster(raster, offset, rect.Width, rect.Height);
Thanks for help.
Tom
Compilation of LibTiff\LibJpeg\Internal\phuff_entropy_decoder.cs fails using Visual Studio 2015.
LibTiff\LibJpeg\Internal\phuff_entropy_decoder.cs(458,21,458,68): error CS0675: Bitwise-or operator used on a sign-extended operand; consider casting to a smaller unsigned type first
I can suppress the error but am not familiar with the code so I don't know whether or not this is a real issue.
I was checking the compatibility of some files with this library and I found a bug. The attached file has the tags XPTitle and XPComment (40091 and 40092), which are shown by Windows' file properties dialog. This library will overshoot when iterating over known tags for each unknown tag, leading to the erroneous out of order check.
The simple fix is to add "fix--;" after the first "haveunknowntags = true;" in Tiff.cs. A better fix would be to replace the ill advised iterating over the known tag list with a simple hashtable.
By the way I also encountered bugs involving bigtiff support that appear to have been fixed on github but not in the official release. Do you plan to update the official release with these fixes? Thanks.
Dear Team,
Thanks for creating this library in the first place, it a really great one. When using version 2.3.xx, everything work fine, however once we update the new lib, we notice one bug.
We use Tiff class SetField() to set tag to the tiff image, the tag with we test with is "SOFTWARE" tag that causing the problem, the value that we put in is "V3.1". we then CheckpointDirectory() to save the new file => tiff image become black (corrupted). However if we set the value into "V31", everything is working find. Do you happen to experience something like this before? Why is that '.' char is causing the problem?
Here is our sample code
`private static Tiff.TiffExtendProc m_parentExtender;
public static void embedTags(string fileName, List tags)
{
m_parentExtender = Tiff.SetTagExtender(TagExtender);
string existingTiffName = string.Format("{0}~.tif", fileName);
File.Copy(fileName, existingTiffName, true);
using (Tiff image = Tiff.Open(existingTiffName, "a"))
{
image.SetDirectory(0);
foreach (var t in tags)
{
TiffTag tag = (TiffTag)t.Id;
image.SetField(tag, t.Value);
}
image.CheckpointDirectory(); //after this line new tiff image is create+tag is embedded, and it now become black.
}
}`
0001-Currently-signed-and-unsigned-rational-values-are-be.zip
When reading an unsigned rational value it will read but the numerator and denominator as signed integers so for large values they will be read incorrectly. I created a simple fix for this already.
Is jpeg 2000 support enabled for tiff files?
If not how can this be done?
The title pretty much says it all.
I'm constructing an XML packet using XmpCore, which comes out as a string in C# terms. An attempt to call myTiff.SetField(TiffTag.XMLPACKET, xmpPacket)
throws an error with a stack trace which shows that it is trying to feed my input into Int.TryParse( )
for reasons I cannot figure out, despite looking though the source code for SetField( )
. It certainly appears to be the case that the parser inside SetField
thinks the type of TiffTag.XMLPACKET is Int rather than Byte; can't tell from the stack trace whether it thinks it's a single Int or a stack of N of them.
I looked into casting the string to a FieldValue
or FieldValue[ ]
, so as to be able to use the GetBytes( )
method, but without success.
This is not critical to me; I've worked around this by implementing a custom tag (as described in the samples) of type Byte, and I think it's working fine. (An aside, there... in your samples on custom tags, you use -1
instead of TiffFieldInfo.Variable
, which seems like very poor practice, especially in an example. And the documentation on TiffFieldInfo.Variable2
leaves me mystified on what I would want it for and might benefit from a rewrite.)
But the issue with XMLPACKET still seemed worth bringing to your attention.
Cheers!
Added libtiff.net using NuGet to my solution today. Unfortunately I could not use it directly, because the assembly was not StrongName signed.
Please enable solutions that are itself StrongName signed to use libtiff.net directly by sign your assembl(y|ies).
Btw: thanks for your work porting this library to managed C#!
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.