How to split a multi-frame TIFF image in pagewise in .NET 2.0? - c#-2.0

I want to split multlipage tiff image in page wise.
I have written following code.
Dim pagecount, ImagePageCount As Integer
Dim activePage As Integer
Dim sourceImage As System.Drawing.Image = Nothing
Dim fImage As Bitmap = Nothing
Dim pageLoad As Boolean = False
Try
fImage = New Bitmap(tempFilePath)
sourceImage = fImage
pagecount = sourceImage.GetFrameCount(FrameDimension.Page)
pageLoad = True
Catch ex As Exception
pageLoad = False
Throw
End Try
Try
If pageLoad = True Then
If pagecount <> 0 Then
For ImagePageCount = 0 To pagecount - 1
sourceImage.SelectActiveFrame(FrameDimension.Page, ImagePageCount)
activePage = ImagePageCount + 1
Dim img1 As Drawing.Bitmap = CType(sourceImage.Clone, Drawing.Bitmap)
Dim tempPageFile As String = Path.Combine(Path.GetTempPath(), String.Format("{0}_{1}_{2:00000000}_{3}.tif", Convert.ToString(indexEntry.GetFrameNumber()), Convert.ToString(indexEntry.GetCaseNumber()), document.ISN, activePage))
img1.Save(tempPageFile)
zip.AddFile(tempPageFile, "")
Next
End If
sourceImage.Dispose()
fImage.Dispose()
End If
Mostly it works but when image with different size(in pixels) came that time sourceImage.SelectActiveFrame(FrameDimension.Page, ImagePageCount) fails.
I have observed that it happens only when first page's size is smaller than rest of the pages.
Any thoughts on this.
Thanks

The page size should not affect it. Testing similar code with a 3-page TIFF file where the first page was smaller than the other 2 worked in a .NET 2.0 program.
However, since TIFF can have a different compression format for each page, most likely the failure happens if you hit a page that's not supported by GDI+ on your operating system.
The test file that worked has all 3 pages saved with LZW compression.
See the following post for a discussion of how different Windows versions support different sub-types of TIFF:
C# Generic GDI+ Error when using Image.Save()

Related

Change font size; checklist box items are on top of each other

We remote into our work environment. When working from home the monitor scale looks different than at work. I've spent hours trying to get them to look the same and failed. So I would like to add a scaler(font increaser/decreaser) to my program. The concept is to change the font size of the form and the rest will scale. It seems to work fine except the checklist box(See screenshots). The items are almost stacked on top of each other. I can't seem to get it to update or redraw itself. I'm writing in VB.NET by the way(I know:)). I've tried CheckListBox.Update(); CheckListBox.Refresh(); CheckListBox.ResetText() and all have failed. Is there a way to separate them? perhaps my approach is wrong. What do you think?
Initial Run Tiny
Scale up
VB.NET
Private Sub Btn_Scale_Up_Click(sender As Object, e As EventArgs) Handles Btn_Scale_Up.Click
Dim FntSize as Integer = Font.Size
FntSize += 1
Me.Font = New Font("Arial", FntSize)
FrmResize.ResizeAllControls(Me)
'CLBox_ColumsForDescription.Update()
'CLBox_ColumnsForDescription.Refresh()
'CLBox_ColumnsForDescription.ResetText()
Me.Update()
End Sub
Private Sub Btn_Scale_Down_Click(sender As Object, e As EventArgs) Handles Btn_Scale_Down.Click
Dim FntSize as Integer = Font.Size
FntSize -= 1
Me.Font = New Font("Arial", FntSize)
FrmResize.ResizeAllControls(Me)
'CLBox_ColumsForDescription.Update()
'CLBox_ColumnsForDescription.Refresh()
'CLBox_ColumnsForDescription.ResetText()
Me.Update()
End Sub
Public Class ResizerForm1
Public Sub ResizeAllControls(ThisCtrl as Control)
For Each Ctl as Control in ThisCtrl.Controls
If Ctl.Name.Contains("CLBox_ColumsForDescription") Then
'--Size
Ctl.Width = Int(ParentWidth - Ctl.Location.X - 30)
Ctl.Height = Int(ParentHeight - Ctl.Location.Y - (ParentHeight - Ctl.Parent.Controls.Item("Btn_Below").Location.Y))
'--Position
Ctl.Top = Int(Ctl.Parent.Controls.Item("TxtBox_Above").Location.Y + Ctl.Parent.Controls.Item("TxtBox_Above").Height + 5)
Ctl.Left = 15
'Ctl.Update()
'Ctl.Refresh()
End If
Next
End Sub
End Class

Zebra Printer - Not Printing PNG Stream *Provided my own answer*

I think I'm very close to getting this to print. However it still isn't. There is no exception thrown and it does seem to be hitting the zebra printer, but nothing. Its a long shot as I think most people are in the same position I am and know little about it. Any help anyone can give no matter how small will be welcomed, I'm losing the will to live
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
using (var stream = new MemoryStream())
{
if (responseStream == null)
{
return;
}
responseStream.CopyTo(stream);
stream.Position = 0;
using (var zipout = ZipFile.Read(stream))
{
using (var ms = new MemoryStream())
{
foreach (var e in zipout.Where(e => e.FileName.Contains(".png")))
{
e.Extract(ms);
}
if (ms.Length <= 0)
{
return;
}
var binaryData = ms.ToArray();
byte[] compressedFileData;
// Compress the data using the LZ77 algorithm.
using (var outStream = new MemoryStream())
{
using (var compress = new DeflateStream(outStream, CompressionMode.Compress, true))
{
compress.Write(binaryData, 0, binaryData.Length);
compress.Flush();
compress.Close();
}
compressedFileData = outStream.ToArray();
}
// Encode the compressed data using the MIME Base64 algorithm.
var base64 = Convert.ToBase64String(compressedFileData);
// Calculate a CRC across the encoded data.
var crc = Calc(Convert.FromBase64String(base64));
// Add a unique header to differentiate the new format from the existing ASCII hexadecimal encoding.
var finalData = string.Format(":Z64:{0}:{1}", base64, crc);
var zplToSend = "~DYR:LOGO,P,P," + finalData.Length + ",," + finalData;
const string PrintImage = "^XA^FO0,0^IMR:LOGO.PNG^FS^XZ";
try
{
var client = new System.Net.Sockets.TcpClient();
client.Connect(IpAddress, Port);
var writer = new StreamWriter(client.GetStream(), Encoding.UTF8);
writer.Write(zplToSend);
writer.Flush();
writer.Write(PrintImage);
writer.Close();
client.Close();
}
catch (Exception ex)
{
// Catch Exception
}
}
}
}
}
}
private static ushort Calc(byte[] data)
{
ushort wCrc = 0;
for (var i = 0; i < data.Length; i++)
{
wCrc ^= (ushort)(data[i] << 8);
for (var j = 0; j < 8; j++)
{
if ((wCrc & 0x8000) != 0)
{
wCrc = (ushort)((wCrc << 1) ^ 0x1021);
}
else
{
wCrc <<= 1;
}
}
}
return wCrc;
}
The following code is working for me. The issue was the commands, these are very very important! Overview of the command I have used below, more can be found here
PrintImage
^XA
Start Format Description The ^XA command is used at the beginning of ZPL II code. It is the opening bracket and indicates the start of a new label format. This command is substituted with a single ASCII control character STX (control-B, hexadecimal 02). Format ^XA Comments Valid ZPL II format requires that label formats should start with the ^XA command and end with the ^XZ command.
^FO
Field Origin Description The ^FO command sets a field origin, relative to the label home (^LH) position. ^FO sets the upper-left corner of the field area by defining points along the x-axis and y-axis independent of the rotation. Format ^FOx,y,z
x = x-axis location (in dots) Accepted Values: 0 to 32000 Default
Value: 0
y = y-axis location (in dots) Accepted Values: 0 to 32000
Default Value: 0
z = justification The z parameter is only
supported in firmware versions V60.14.x, V50.14.x, or later. Accepted
Values: 0 = left justification 1 = right justification 2 = auto
justification (script dependent) Default Value: last accepted ^FW
value or ^FW default
^IM
Image Move Description The ^IM command performs a direct move of an image from storage area into the bitmap. The command is identical to the ^XG command (Recall Graphic), except there are no sizing parameters. Format ^IMd:o.x
d = location of stored object Accepted Values: R:, E:, B:, and A: Default Value: search priority
o = object name Accepted Values: 1 to 8 alphanumeric characters Default Value: if a name is not specified, UNKNOWN is used
x = extension Fixed Value: .GRF, .PNG
^FS
Field Separator Description The ^FS command denotes the end of the field definition. Alternatively, ^FS command can also be issued as a single ASCII control code SI (Control-O, hexadecimal 0F). Format ^FS
^XZ
End Format Description The ^XZ command is the ending (closing) bracket. It indicates the end of a label format. When this command is received, a label prints. This command can also be issued as a single ASCII control character ETX (Control-C, hexadecimal 03). Format ^XZ Comments Label formats must start with the ^XA command and end with the ^XZ command to be in valid ZPL II format.
zplToSend
^MN
Media Tracking Description This command specifies the media type being used and the black mark offset in dots. This bulleted list shows the types of media associated with this command:
Continuous Media – this media has no physical characteristic (such as a web, notch, perforation, black mark) to separate labels. Label length is determined by the ^LL command.
Continuous Media, variable length – same as Continuous Media, but if portions of the printed label fall outside of the defined label length, the label size will automatically be extended to contain them. This label length extension applies only to the current label. Note that ^MNV still requires the use of the ^LL command to define the initial desired label length.
Non-continuous Media – this media has some type of physical characteristic (such as web, notch, perforation, black mark) to separate the labels.
Format ^MNa,b
a = media being used Accepted Values: N = continuous media Y = non-continuous media web sensing d, e W = non-continuous media web sensing d, e M = non-continuous media mark sensing A = auto-detects the type of media during calibration d, f V = continuous media, variable length g Default Value: a value must be entered or the command is ignored
b = black mark offset in dots This sets the expected location of the media mark relative to the point of separation between documents. If set to 0, the media mark is expected to be found at the point of separation. (i.e., the perforation, cut point, etc.) All values are listed in dots. This parameter is ignored unless the a parameter is set to M. If this parameter is missing, the default value is used. Accepted Values: -80 to 283 for direct-thermal only printers -240 to 566 for 600 dpi printers -75 to 283 for KR403 printers -120 to 283 for all other printers Default Value: 0
~DY
Download Objects Description The ~DY command downloads to the printer graphic objects or fonts in any supported format. This command can be used in place of ~DG for more saving and loading options. ~DY is the preferred command to download TrueType fonts on printers with firmware later than X.13. It is faster than ~DU. The ~DY command also supports downloading wireless certificate files. Format ~DYd:f,b,x,t,w,data
Note
When using certificate files, your printer supports:
- Using Privacy Enhanced Mail (PEM) formatted certificate files.
- Using the client certificate and private key as two files, each downloaded separately.
- Using exportable PAC files for EAP-FAST.
- Zebra recommends using Linear sty
d = file location .NRD and .PAC files reside on E: in firmware versions V60.15.x, V50.15.x, or later. Accepted Values: R:, E:, B:, and A: Default Value: R:
f = file name Accepted Values: 1 to 8 alphanumeric characters Default Value: if a name is not specified, UNKNOWN is used
b = format downloaded in data field .TTE and .TTF are only supported in firmware versions V60.14.x, V50.14.x, or later. Accepted Values: A = uncompressed (ZB64, ASCII) B = uncompressed (.TTE, .TTF, binary) C = AR-compressed (used only by Zebra’s BAR-ONE® v5) P = portable network graphic (.PNG) - ZB64 encoded Default Value: a value must be specified
clearDownLabel
^ID
Description The ^ID command deletes objects, graphics, fonts, and stored formats from storage areas. Objects can be deleted selectively or in groups. This command can be used within a printing format to delete objects before saving new ones, or in a stand-alone format to delete objects.
The image name and extension support the use of the asterisk (*) as a wild card. This allows you to easily delete a selected groups of objects. Format ^IDd:o.x
d = location of stored object Accepted Values: R:, E:, B:, and A: Default Value: R:
o = object name Accepted Values: any 1 to 8 character name Default Value: if a name is not specified, UNKNOWN is used
x = extension Accepted Values: any extension conforming to Zebra conventions
Default Value: .GRF
const string PrintImage = "^XA^FO0,0,0^IME:LOGO.PNG^FS^XZ";
var zplImageData = string.Empty;
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
using (var stream = new MemoryStream())
{
if (responseStream == null)
{
return;
}
responseStream.CopyTo(stream);
stream.Position = 0;
using (var zipout = ZipFile.Read(stream))
{
using (var ms = new MemoryStream())
{
foreach (var e in zipout.Where(e => e.FileName.Contains(".png")))
{
e.Extract(ms);
}
if (ms.Length <= 0)
{
return;
}
var binaryData = ms.ToArray();
foreach (var b in binaryData)
{
var hexRep = string.Format("{0:X}", b);
if (hexRep.Length == 1)
{
hexRep = "0" + hexRep;
}
zplImageData += hexRep;
}
var zplToSend = "^XA" + "^FO0,0,0" + "^MNN" + "~DYE:LOGO,P,P," + binaryData.Length + ",," + zplImageData + "^XZ";
var label = GenerateStreamFromString(zplToSend);
var client = new System.Net.Sockets.TcpClient();
client.Connect(IpAddress, Port);
label.CopyTo(client.GetStream());
label.Flush();
client.Close();
var cmd = GenerateStreamFromString(PrintImage);
var client2 = new System.Net.Sockets.TcpClient();
client2.Connect(IpAddress, Port);
cmd.CopyTo(client2.GetStream());
cmd.Flush();
client2.Close();var clearDownLabel = GenerateStreamFromString("^XA^IDR:LOGO.PNG^FS^XZ");
var client3 = new System.Net.Sockets.TcpClient();
client3.Connect(IpAddress, Port);
clearDownLabel.CopyTo(client3.GetStream());
clearDownLabel.Flush();
client3.Close();
}
}
}
}
}
}
Easy once you know how.
Zebra ZPL logo example in base64
Python3
import crcmod
import base64
crc16 = crcmod.predefined.mkCrcFun('xmodem')
s = hex(crc16(ZPL_LOGO.encode()))[2:]
print (f"crc16: {s}")
Poorly documented may I say the least

DirectX Device::CreateTexture2D() crashes when calling with all 3 params

I am gonna try to render a 2D Texture from opencv::Mat to a Texture in DX11 and also to a shaderesource afterwars. The Problem is, the program crashes on Device::CreateTexture2D() and I can't figure out why. I researched the whole day, I just don't see whats wrong here.
Furthermore, the Problem seems not to be the cv::Mat as Resource, because I have tried also this example here: D3D11 CreateTexture2D in 32 bit format with the chess-example as resource for the texture... and the functions still crashes, when calling with the 3rd param.
I found others, who had Problems with that function, sometimes the Problem was because that SysMemPitch was not set for 2D Textures but that's not the case here unfortunately.
Error Output: First-chance exception at 0x692EF11E (igd10iumd32.dll) in ARift.exe: 0xC0000005: Access violation reading location 0x03438000.
Unhandled exception at 0x692EF11E (igd10iumd32.dll) in ARift.exe: 0xC0000005: Access violation reading location 0x03438000.
here is the relevant code:
bool Texture::InitCameraStream(ID3D11Device* device, ARiftControl* arift_control)
{
D3D11_TEXTURE2D_DESC td;
ZeroMemory(&td, sizeof(td));
td.ArraySize = 1;
td.BindFlags = D3D11_BIND_SHADER_RESOURCE;
td.Usage = D3D11_USAGE_DYNAMIC;
td.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
td.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
td.Height = arift_control->picture_1_.size().height;
td.Width = arift_control->picture_1_.size().width;
td.MipLevels = 1;
td.MiscFlags = 0;
td.SampleDesc.Count = 1;
td.SampleDesc.Quality = 0;
D3D11_SUBRESOURCE_DATA srInitData;
srInitData.pSysMem = arift_control->picture_1_.ptr();
srInitData.SysMemPitch = arift_control->picture_1_.size().width * 4;
ID3D11Texture2D* tex = 0;
if ((device->CreateTexture2D(&td, &srInitData, NULL) == S_FALSE));
{
std::cerr << "Texture Description: OK " << std::endl << "Subresource: OK" << std::endl;
}
if (FAILED(device->CreateTexture2D(&td, &srInitData, &tex)));
{
std::cerr << "Error: Texture could not be created! "<< std::endl;
return false;
}
// Create the shader-resource view
D3D10_SHADER_RESOURCE_VIEW_DESC srDesc;
srDesc.Format = td.Format;
srDesc.ViewDimension = D3D10_SRV_DIMENSION_TEXTURE2D;
srDesc.Texture2D.MostDetailedMip = 0;
srDesc.Texture2D.MipLevels = 1;
if (FAILED(device->CreateShaderResourceView(tex, NULL, &texture_)));
{
std::cerr << "Can't create Shader Resource View" << std::endl;
return false;
}
return true;
}
CreateTexture2D Returns S_FALSE when the first 2 Parameters are valid, and passing 0 as the 3rd param. So in my case, it also Returns S_FALSE the first time, so the Debug Output appears. When calling CreateTexture2D with the 3rd param (the TExture COM object), it crashed. I have absolutely no idea anymore.
Furthermore, I tried to Setup Debugging with DirectX and followed that tutorial: http://blog.rthand.com/post/2010/10/25/Capture-DirectX-1011-debug-output-to-Visual-Studio.aspx - but I can't see a "Debug" window in my Project Properties in Visual Studio 2013. So I still get to "igd10iumd32.pdb not loaded" window, after the program crashes.
Edit: at least I could fix the issue with the additional D3D debug Outputs for now. In my Visual Studio 2013 I had to set the following: Project Properties -> Debugging -> Debug Type -> Mixed for getting the Additional D3D logs :)
Can anyone help here? It's really frustrating, just getting stuck on that single function the whole day ..
Many thanks!
Max
Your input texture data passed in D3D11_SUBRESOURCE_DATA is not sufficiently sized. In your comment, you said that the input image data is 900x1600, and the link is a JPEG. However, you are specifying to D3D that the data format is DXGI_FORMAT_B8G8R8A8_UNORM. JPEG is a compressed format, thus, the data stream will be smaller than it would be in BGRA format. When your drive (igd10iumd32.dll) attempts to read this input stream, it crashes because the buffer is not as large as you told D3D it was.
You can use D3DX11CreateTextureFromFile to load JPEG data. There are also some free image conversion libraries you can use to convert the JPEG into a D3D natively compatible format.

Java ImageIO Read and Write compressed Tiff files with CIE lab colorspace

I actually try to read and write compressed tif-files with CIE Lab colorspace.
Unfortunally if I try to just read and after this write the tif back to the HDD the color is different from the soure tif.
Is the ImageIO lib able to read and write compressed tif files with CIE lab color space?
If it is possible I fear that something is wrong with the code. In the singleTiffs list are at least one tiff-ImageInputStream which is created in this way:
ImageIO.createImageInputStream(testTiff)
Would be great if someone could help me. Thanks a lot!
// Get iterator for input images
Iterator<ImageInputStream> iterator = singleTiffs.iterator();
// Get tif writer and set output to file
Iterator writers = ImageIO.getImageWritersByFormatName("tiff");
ImageWriter writer = (ImageWriter) writers.next();
ImageOutputStream ios = ImageIO.createImageOutputStream(newMultiPageTIFF);
writer.setOutput(ios);
// Write each image out to the new file
boolean firstImage = true;
while(iterator.hasNext())
{
ImageInputStream iis = iterator.next();
// Get a reader for the stream
Iterator readers = ImageIO.getImageReaders(iis);
ImageReader reader = (ImageReader) readers.next();
reader.setInput(iis);
// Read the stream metadata
// IIOMetadata streamMetadata = reader.getStreamMetadata();
// Read the image metadata - we are assuming there is only one image
// in the tiff
IIOMetadata imageMetadata = reader.getImageMetadata(0);
// Set up the writeParam
TIFFImageWriteParam tiffWriteParam = new TIFFImageWriteParam(Locale.US);
tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_COPY_FROM_METADATA);
BufferedImage bi = reader.read(0, null);
IIOImage image = new IIOImage(bi, null, imageMetadata);
if(firstImage == false)
writer.writeInsert(-1, image, tiffWriteParam);
else
{
writer.write(null, image, tiffWriteParam);
firstImage = false;
}
// Done writing all images for this image
reader.dispose();
}
// End writing of all files
writer.dispose();

Flipping image causes massive RAM/CPU uses with AForge.net

Hey all i am trying to figure out why when i flip the image it uses a LOT of RAM and CPU (its an quad core i7)
I use this code:
Dim filter As New RotateBilinear(180, True)
image = Filter.Apply(image)
If bIsToRecord Then
If writer Is Nothing Then
Dim [date] As DateTime = DateTime.Now
Dim fileName As [String] = [String].Format("{0},{1}.avi",[date].Minute, [date].Second)
Try
OpenWriter(fileName, image.Width, image.Height)
Catch ex As Exception
If writer IsNot Nothing Then
writer.Dispose()
writer = Nothing
End If
End Try
End If
Try
If radioButton1.Checked Then
writer.AddFrame(image)
Else
mVideoFileWriter.WriteVideoFrame(image)
End If
Catch ex As Exception
System.Diagnostics.Trace.WriteLine(ex.ToString())
End Try
End If
That is WITHOUT flipping the images
WITH the flipping...
Each screenshot was for 30 seconds.
What could be causing this?

Resources