Posts Tagged Image
Capture an Image of the Desktop, Specific Screen or Portion of a Screen with C#
Posted by Kelly's Chronicles in .NET, C# on July 21, 2014
So today is my birthday. It has been a wild ride this last 46 years. Lets hope that things continue to get better.
So this is my entire class for capturing screens and desktop appearance to an image file or to print them. I use this class quite often in my error management, saving or emailing the output should errors occur so I can get a good idea of what was going on at the time an error occurs. Why? Because often end users or business analysts, though they are trying their best, sometimes can’t describe in detail how to reproduce what occurred. I suggest using this in conjunction with a logging class as well so that you can replicate the steps needed. The image file is also very handy in reconstructing what a user was or was not doing which, as a coder, can literally save your ass on occasion. So here it is. It is well commented and pretty straight forward.
using System.Windows.Forms;
using System;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Drawing.Imaging;
public class clsScreenCapture
{
private System.Drawing.Printing.PrintDocument Pd = new System.Drawing.Printing.PrintDocument();
private PictureBox PicForm = new PictureBox();
/// Creates an Image object containing a screen shot of the entire desktop
public Image CaptureScreen()
{
return CaptureWindow(User32.GetDesktopWindow());
} //CaptureScreen
/// Creates an Image object containing a screen shot of a specific window
public Image CaptureWindow(IntPtr handle)
{
int SRCCOPY = 0xCC0020;
// get te hDC of the target window
IntPtr hdcSrc = User32.GetWindowDC(handle);
// get the size
User32.RECT windowRect = new User32.RECT();
User32.GetWindowRect(handle, ref windowRect);
int width = windowRect.right – windowRect.left;
int height = windowRect.bottom – windowRect.top;
// create a device context we can copy to
IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc);
// create a bitmap we can copy it to,
// using GetDeviceCaps to get the width/height
IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc, width, height);
// select the bitmap object
IntPtr hOld = GDI32.SelectObject(hdcDest, hBitmap);
// bitblt over
GDI32.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, SRCCOPY);
// restore selection
GDI32.SelectObject(hdcDest, hOld);
// clean up
GDI32.DeleteDC(hdcDest);
User32.ReleaseDC(handle, hdcSrc);
// get a .NET image object for it
Image img = Image.FromHbitmap(hBitmap);
// free up the Bitmap object
GDI32.DeleteObject(hBitmap);
return img;
} //CaptureWindow
/// Captures a screen shot of a specific window, and saves it to a file
public void CaptureWindowToFile(IntPtr handle, string filename, ImageFormat format)
{
Image img = CaptureWindow(handle);
img.Save(filename, format);
} //CaptureWindowToFile
/// Captures a screen shot of a specific window, and saves it to a file
public void CaptureWindowToPrinter(Form mfForm, ImageFormat format)
{
// Dim img As Image = CaptureScreen()
Image img = CaptureWindow(mfForm.Handle);
try
{
PicForm.Image = img;
if (MessageBox.Show(“Press Yes to Print or No to Copy to your Clipboard (‘No’ will allow pasting into an email or Word document etc).”, “Print or Copy to Clipboard?”, MessageBoxButtons.YesNo) == DialogResult.Yes)
{
Pd.Print();
}
else
{
Clipboard.SetDataObject(img, true);
}
}
catch (Exception ex)
{
string a = “vfdgsfg”;
}
} //CaptureWindowToPrinter
private void pd_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
//—————————————————————
// this procedure handles events raised by the printer object pd
//—————————————————————
e.Graphics.DrawImageUnscaled(PicForm.Image, 0, 0); //send image to printer – upper left position
e.HasMorePages = false; //this is the last page to print
}
/// Captures a screen shot of the entire desktop, and saves it to a file
public void CaptureScreenToFile(string filename, ImageFormat format)
{
Image img = CaptureScreen();
img.Save(filename, format);
} //CaptureScreenToFile
public Bitmap CaptureDeskTopRectangle(Rectangle CapRect, int CapRectWidth, int CapRectHeight)
{
/// Returns BitMap of the region of the desktop, similar to CaptureWindow, but can be used to
/// create a snapshot of the desktop when no handle is present, by passing in a rectangle
/// Grabs snapshot of entire desktop, then crops it using the passed in rectangle’s coordinates
clsScreenCapture SC = new clsScreenCapture();
Bitmap bmpImage = new Bitmap(SC.CaptureScreen());
Bitmap bmpCrop = new Bitmap(CapRectWidth, CapRectHeight, bmpImage.PixelFormat);
Rectangle recCrop = new Rectangle(CapRect.X, CapRect.Y, CapRectWidth, CapRectHeight);
Graphics gphCrop = Graphics.FromImage(bmpCrop);
Rectangle recDest = new Rectangle(0, 0, CapRectWidth, CapRectHeight);
gphCrop.DrawImage(bmpImage, recDest, recCrop.X, recCrop.Y, recCrop.Width, recCrop.Height, GraphicsUnit.Pixel);
return bmpCrop;
}
/// Helper class containing Gdi32 API functions
private class GDI32
{
public int SRCCOPY = 0xCC0020;
// BitBlt dwRop parameter
[System.Runtime.InteropServices.DllImport(“gdi32.dll”, EntryPoint=”BitBlt”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
public static extern Int32 BitBlt(IntPtr hDestDC, Int32 x, Int32 y, Int32 nWidth, Int32 nHeight, IntPtr hSrcDC, Int32 xSrc, Int32 ySrc, Int32 dwRop);
[System.Runtime.InteropServices.DllImport(“gdi32.dll”, EntryPoint=”CreateCompatibleBitmap”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, Int32 nWidth, Int32 nHeight);
[System.Runtime.InteropServices.DllImport(“gdi32.dll”, EntryPoint=”CreateCompatibleDC”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
public static extern IntPtr CreateCompatibleDC(IntPtr hdc);
[System.Runtime.InteropServices.DllImport(“gdi32.dll”, EntryPoint=”DeleteDC”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
public static extern Int32 DeleteDC(IntPtr hdc);
[System.Runtime.InteropServices.DllImport(“gdi32.dll”, EntryPoint=”DeleteObject”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
public static extern Int32 DeleteObject(IntPtr hObject);
[System.Runtime.InteropServices.DllImport(“gdi32.dll”, EntryPoint=”SelectObject”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hObject);
} //GDI32
/// Helper class containing User32 API functions
public class User32
{
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
} //RECT
[System.Runtime.InteropServices.DllImport(“user32.dll”, EntryPoint=”GetDesktopWindow”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
public static extern IntPtr GetDesktopWindow();
[System.Runtime.InteropServices.DllImport(“user32.dll”, EntryPoint=”GetWindowDC”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
public static extern IntPtr GetWindowDC(IntPtr hwnd);
[System.Runtime.InteropServices.DllImport(“user32.dll”, EntryPoint=”ReleaseDC”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
public static extern Int32 ReleaseDC(IntPtr hwnd, IntPtr hdc);
[System.Runtime.InteropServices.DllImport(“user32.dll”, EntryPoint=”GetWindowRect”, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Ansi, SetLastError=true)]
public static extern Int32 GetWindowRect(IntPtr hwnd, ref RECT lpRect);
} //User32
public clsScreenCapture()
{
SubscribeToEvents();
}
// event handler wireups:
private bool EventsSubscribed = false;
private void SubscribeToEvents()
{
if (EventsSubscribed)
return;
else
EventsSubscribed = true;
Pd.PrintPage += pd_PrintPage;
}
}
.NET, analysts, Ansi, appearance, BitBlt, Bitmap, bmpCrop, bmpImage, c#, CapRect, CapRectWidth, Capture, CaptureDeskTopRectangle, Captures, CaptureScreenToFile, CaptureWindowToFile, CaptureWindowToPrinter, CharSet, Clipboard, clsScreenCapture, conjunction, Context, Copy, CreateCompatibleBitmap, CreateCompatibleDC, Creates, DeleteDC, DeleteObject, Desktop, device, DialogResult, DllImport, DrawImage, dwRop, EntryPoint, error, errors, event, events, Exception, extern, filename, Form, Forms, FromHbitmap, FromImage, GetDeviceCaps, GetWindowDC, GetWindowRect, gphCrop, Grabs, graphics, GraphicsUnit, Handle, handler, HasMorePages, hBitmap, hdcDest, hdcSrc, Helper, hObject, hwnd, Image, ImageFormat, InteropServices, IntPtr, Lets, management, MessageBox, MessageBoxButtons, mfForm, nWidth, output, parameter, pd_PrintPage, PicForm, PictureBox, Pixel, PixelFormat, Portion, Print, PrintDocument, printer, PrintPage, PrintPageEventArgs, procedure, recCrop, recDest, RECT, Rectangle, region, ReleaseDC, Returns, Runtime, Save, Selection, SelectObject, sender, Sequential, SetDataObject, SetLastError, size, snapshot, Specific, SRCCOPY, StructLayout, SubscribeToEvents, System, user, users, Width, windowRect, Windows, Word, YesNo
Get or Write Image Metadata with vb.net
Posted by Kelly's Chronicles in .NET, vb.net on September 1, 2011
I recently started a new contract with a local company and their project is quite image intensive. One of the tasks set before me was to store custom data in an image. Things such as the title, comments and keywords. Turned out to be quite an extensive undertaking. With the help of some other sources, I came up with this code. Ironically as it turned out we can’t use my solution because of some issues with custom image formats that are not respected in Microsoft Windows. But it is here for you! I will post the C# version soon. Also pay attention to your encoding. This was an issue that tripped me up here for a while.
Imports System.Collections.Generic
Imports System.Text
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Reflection
Imports System.IO
Public Class clsReadMetaData
Public Function ReadEXIFMetadata(ByVal filepath As String) As ImageMetadata
Dim fs As New FileStream(filepath, FileMode.Open, FileAccess.Read)
Dim image__1 As Image = Image.FromStream(fs)
Dim imagePropertyItems As PropertyItem() = image__1.PropertyItems
Dim imageMetadata As New ImageMetadata()
For Each pi As PropertyItem In imagePropertyItems
Select Case CType(pi.Id, EXIFProperty)
Case EXIFProperty.Title
imageMetadata.Title = Encoding.Unicode.GetString(pi.Value)
‘imageMetadata.Title = Encoding.UTF32.GetString(pi.Value)
Exit Select
Case EXIFProperty.Author
imageMetadata.Author = Encoding.Unicode.GetString(pi.Value)
‘imageMetadata.Author = Encoding.UTF8.GetString(pi.Value)
Exit Select
Case EXIFProperty.Keywords
imageMetadata.Keywords = Encoding.Unicode.GetString(pi.Value)
‘imageMetadata.Keywords = Encoding.UTF8.GetString(pi.Value)
Exit Select
Case EXIFProperty.Comments
imageMetadata.Comments = Encoding.Unicode.GetString(pi.Value)
‘imageMetadata.Comments = Encoding.UTF8.GetString(pi.Value)
Exit Select
Case Else
Exit Select
End Select
Next
fs.Close()
Return imageMetadata
End Function
Public Sub SaveEXIFMetadata(ByVal image As Image, ByVal metadata As ImageMetadata, ByVal filepath As String)
SaveEXIFMetadataProperty(image, EXIFProperty.Title, metadata.Title, filepath)
SaveEXIFMetadataProperty(image, EXIFProperty.Author, metadata.Author, filepath)
SaveEXIFMetadataProperty(image, EXIFProperty.Keywords, metadata.Keywords, filepath)
SaveEXIFMetadataProperty(image, EXIFProperty.Comments, metadata.Comments, filepath)
End Sub
Private Sub SaveEXIFMetadataProperty(ByVal image As Image, ByVal [property] As EXIFProperty, ByVal propertyValue As String, ByVal filepath As String)
Dim propertyItem As PropertyItem = CreatePropertyItem()
propertyItem.Id = CInt([property])
‘ Type=1 means Array of Bytes.
propertyItem.Type = 2
propertyItem.Len = propertyValue.Length
‘propertyItem.Value = Encoding.Unicode.GetBytes(propertyValue)
propertyItem.Value = Encoding.UTF8.GetBytes(propertyValue)
image.SetPropertyItem(propertyItem)
image.Save(filepath)
End Sub
Private Function CreatePropertyItem() As PropertyItem
Dim ci As System.Reflection.ConstructorInfo = GetType(PropertyItem).GetConstructor(BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.[Public], Nothing, New Type() {}, Nothing)
Return DirectCast(ci.Invoke(Nothing), PropertyItem)
End Function
End Class
Public Enum EXIFProperty
Title = 40091
Author = 40093
Keywords = 40094
Comments = 40092
End Enum
Public Class ImageMetadata
Private _title As String = String.Empty
Private _author As String = String.Empty
Private _keywords As String = String.Empty
Private _comments As String = String.Empty
Public Sub New()
Me._title = String.Empty
Me._author = String.Empty
Me._keywords = String.Empty
Me._comments = String.Empty
End Sub
Public Sub New(ByVal title As String, ByVal author As String, ByVal keywords As String, ByVal comments As String)
Me._title = title
Me._author = author
Me._keywords = keywords
Me._comments = comments
End Sub
Public Property Title() As String
Get
Return Me._title
End Get
Set(ByVal value As String)
Me._title = value
End Set
End Property
Public Property Author() As String
Get
Return Me._author
End Get
Set(ByVal value As String)
Me._author = value
End Set
End Property
Public Property Keywords() As String
Get
Return Me._keywords
End Get
Set(ByVal value As String)
Me._keywords = value
End Set
End Property
Public Property Comments() As String
Get
Return Me._comments
End Get
Set(ByVal value As String)
Me._comments = value
End Set
End Property
End Class
.NET Framework, Array, author, BindingFlags, Bytes, Case, Class, Close, Collections, Comments, ConstructorInfo, CreatePropertyItem, custom, Data, DirectCast, Enum, FileMode, filepath, FileStream, FromStream, FUNCTION, Generic, GetBytes, GetConstructor, GetType, Image, ImageMetadata, imagePropertyItems, Imports, instance, Keywords, Length, Metadata, Microsoft, NonPublic, Open, Private, PropertyItem, PropertyItems, propertyValue, Public, Read, ReadEXIFMetadata, Reflection, Return, Save, Select, SetPropertyItem, solution, System, tasks, Text, Title, Type, Unicode, Value, vb.net, version, Windows, Write, _author, _comments, _keywords, _title
Getting Images from Microsoft Office Document Imaging (MODI) with vb.net
Posted by Kelly's Chronicles in .NET, vb.net on July 27, 2011
Hello! It has been a long time since my last blog post and I am happy to be getting back to this. I have missed writing this blog more than you have missed me I guarantee it!
That being said, now that this blog has resumed there will be a few changes. The landscape has changed a bit since my last blog entry. While I will still focus primarily on vb.net code I will also be including what I am working on that is WPF and C# related as well as other .NET related topics. Why? Simply because as my skillset has expanded I wanted to share what I have learned and am learning with you as well. I hope you won’t mind!
Today’s topic revolves around getting images from Microsoft Office Document Imaging (MODI). As you recall I have done a lot of Office automation over the years and I was asked to do this for a friend. As I said, it is good to be back!
add a reference -> Com -> Microsoft Office Document Imaging
Private Sub ConvertMdi2Tif(ByVal ModiFilePath As String)
Dim miDoc As New MODI.Document
Dim myViewer As New MODI.MiDocView
Dim myImg As MODI.Image
Try
Dim Folder As New DirectoryInfo(ModiFilePath)
pbReportGenerate.Minimum = 0
pbReportGenerate.Maximum = Folder.GetFiles(“*.MDI”).Length
pbReportGenerate.Step = 1
pbReportGenerate.Value = pbReportGenerate.Minimum
For Each File As FileInfo In Folder.GetFiles(“*.MDI”)
miDoc.Create(File.FullName)
myViewer.Document = miDoc
For i As Long = 0 To miDoc.Images.Count – 1
Dim tempDoc As New MODI.Document
myImg = miDoc.Images(i)
tempDoc.Create()
tempDoc.Images.Add(myImg, Nothing)
tempDoc.SaveAs(TIFPath & “\” + GetFileNameWithoutExtension(File.FullName) & i & “.Tif”, MiFILE_FORMAT.miFILE_FORMAT_TIFF_LOSSLESS, MiCOMP_LEVEL.miCOMP_LEVEL_HIGH)
tempDoc.Close()
tempDoc = Nothing
Exit For
Next
pbReportGenerate.PerformStep()
Application.DoEvents()
Next
miDoc.Close()
miDoc = Nothing
myViewer.Document = Nothing
myViewer = Nothing
Catch ex As Exception
MsgBox(ex.Message)
End Try
GC.Collect()
End Sub
Private Sub ConvertTif2Bmp(ByVal TIFFilePath As String)
Dim Folder As New DirectoryInfo(TIFFilePath)
Dim index As Long = 0
pbReportGenerate.Minimum = 0
pbReportGenerate.Maximum = Folder.GetFiles(“*.TIF”).Length
pbReportGenerate.Step = 1
pbReportGenerate.Value = pbReportGenerate.Minimum
For Each File As FileInfo In Folder.GetFiles(“*.TIF”)
GC.WaitForPendingFinalizers()
Dim streamBinary As New FileStream(File.FullName, FileMode.Open)
Dim g As System.Drawing.Image = System.Drawing.Image.FromStream(streamBinary)
Dim imgOutput As New Bitmap(g, g.Width, g.Height)
Dim qualityEncoder As Encoder = Encoder.Quality
Dim ratio As EncoderParameter = New EncoderParameter(qualityEncoder, 40)
Dim codecParams As New EncoderParameters(1)
codecParams.Param(0) = ratio
‘bmp.Save(fileName, jpegCodecInfo, codecParams)
Dim encoder1 As ImageCodecInfo = GetEncoderInfo(“image/bmp”)
imgOutput.Save(BMPPath + “\” + GetFileNameWithoutExtension(File.FullName) + “.” & System.Drawing.Imaging.ImageFormat.Bmp.ToString, encoder1, codecParams)
streamBinary.Close()
streamBinary = Nothing
g.Dispose()
g = Nothing
imgOutput.Dispose()
imgOutput = Nothing
pbReportGenerate.PerformStep()
Application.DoEvents()
Next
GC.Collect()
End Sub
WordPress Tags: vb.net,Images,Microsoft,Office,Document,MODI,automation,friend,reference,MiDocView,Image,Folder,DirectoryInfo,Minimum,Maximum,GetFiles,Length,Step,Value,File,FileInfo,Create,FullName,Long,Count,SaveAs,TIFPath,GetFileNameWithoutExtension,MiFILE_FORMAT,MiCOMP_LEVEL,Close,Exit,PerformStep,Application,DoEvents,Catch,Exception,MsgBox,Message,Collect,TIFFilePath,index,WaitForPendingFinalizers,FileStream,FileMode,Open,System,FromStream,Bitmap,Width,Encoder,ratio,EncoderParameter,EncoderParameters,Param,Save,ImageCodecInfo,GetEncoderInfo,BMPPath,ImageFormat,Dispose,blog,miDoc,myViewer,myImg,pbReportGenerate,tempDoc,streamBinary,imgOutput,qualityEncoder,codecParams
Application, automation, Bitmap, blog, BMPPath, Catch, Close, codecParams, Collect, Count, Create, DirectoryInfo, Dispose, Document, DoEvents, Encoder, EncoderParameter, EncoderParameters, Exception, Exit, File, FileInfo, FileMode, FileStream, Folder, friend, FromStream, FullName, GetEncoderInfo, GetFileNameWithoutExtension, GetFiles, Image, ImageCodecInfo, ImageFormat, Images, imgOutput, index, Length, Long, Maximum, Message, MiCOMP_LEVEL, Microsoft, miDoc, MiDocView, MiFILE_FORMAT, Minimum, MODI, MsgBox, myImg, myViewer, Office, Open, Param, pbReportGenerate, PerformStep, qualityEncoder, ratio, reference, Save, SaveAs, Step, streamBinary, System, tempDoc, TIFFilePath, TIFPath, Value, vb.net, WaitForPendingFinalizers, Width
Recent Comments
Archives
- April 2018
- January 2018
- December 2017
- June 2017
- May 2017
- May 2016
- April 2016
- September 2015
- July 2014
- June 2014
- November 2012
- October 2012
- June 2012
- May 2012
- April 2012
- January 2012
- September 2011
- August 2011
- July 2011
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- December 2008
- November 2008
- October 2008
- August 2008
- July 2008
- June 2008
- May 2008
Get or Write Image Metadata with C#
Posted by Kelly's Chronicles in .NET, C#, vb.net on July 15, 2014
Good morning! it’s always fun when old code gets to get used again. And it gave me an opportunity to convert this snippet to C#. Basically what we are trying to do is write or get metadata to an image. As those folks who commented on the previous post noted, this code will not remove existing metadata. It is a problem I still have not found a solution for however. If any of you know the answer please let us know! Anyway here it is converted and still useable after all this time.
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Reflection;
using System.IO;
public class clsReadMetaData
{
public ImageMetadata ReadEXIFMetadata(string filepath)
{
FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
Image image__1 = Image.FromStream(fs);
PropertyItem[] imagePropertyItems = image__1.PropertyItems;
ImageMetadata imageMetadata = new ImageMetadata();
foreach (PropertyItem pi in imagePropertyItems)
{
switch ((EXIFProperty)pi.Id)
{
case EXIFProperty.Title:
imageMetadata.Title = Encoding.Unicode.GetString(pi.Value);
//imageMetadata.Title = Encoding.UTF32.GetString(pi.Value)
break;
case EXIFProperty.Author:
imageMetadata.Author = Encoding.Unicode.GetString(pi.Value);
//imageMetadata.Author = Encoding.UTF8.GetString(pi.Value)
break;
case EXIFProperty.Keywords:
imageMetadata.Keywords = Encoding.Unicode.GetString(pi.Value);
//imageMetadata.Keywords = Encoding.UTF8.GetString(pi.Value)
break;
case EXIFProperty.Comments:
imageMetadata.Comments = Encoding.Unicode.GetString(pi.Value);
//imageMetadata.Comments = Encoding.UTF8.GetString(pi.Value)
break;
default:
break;
}
}
fs.Close();
return imageMetadata;
}
public void SaveEXIFMetadata(Image image, ImageMetadata metadata, string filepath)
{
SaveEXIFMetadataProperty(image, EXIFProperty.Title, metadata.Title, filepath);
SaveEXIFMetadataProperty(image, EXIFProperty.Author, metadata.Author, filepath);
SaveEXIFMetadataProperty(image, EXIFProperty.Keywords, metadata.Keywords, filepath);
SaveEXIFMetadataProperty(image, EXIFProperty.Comments, metadata.Comments, filepath);
}
private void SaveEXIFMetadataProperty(Image image, EXIFProperty property, string propertyValue, string filepath)
{
PropertyItem propertyItem = CreatePropertyItem();
propertyItem.Id = Convert.ToInt32(property);
// Type=1 means Array of Bytes.
propertyItem.Type = 2;
propertyItem.Len = propertyValue.Length;
//propertyItem.Value = Encoding.Unicode.GetBytes(propertyValue)
propertyItem.Value = Encoding.UTF8.GetBytes(propertyValue);
image.SetPropertyItem(propertyItem);
image.Save(filepath);
}
private PropertyItem CreatePropertyItem()
{
System.Reflection.ConstructorInfo ci = typeof(PropertyItem).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public, null, new Type[0], null);
return (PropertyItem)ci.Invoke(null);
}
}
public enum EXIFProperty
{
Title = 40091,
Author = 40093,
Keywords = 40094,
Comments = 40092
}
public class ImageMetadata
{
private string _title = string.Empty;
private string _author = string.Empty;
private string _keywords = string.Empty;
private string _comments = string.Empty;
public ImageMetadata()
{
this._title = string.Empty;
this._author = string.Empty;
this._keywords = string.Empty;
this._comments = string.Empty;
}
public ImageMetadata(string title, string author, string keywords, string comments)
{
this._title = title;
this._author = author;
this._keywords = keywords;
this._comments = comments;
}
public string Title
{
get
{
return this._title;
}
set
{
this._title = value;
}
}
public string Author
{
get
{
return this._author;
}
set
{
this._author = value;
}
}
public string Keywords
{
get
{
return this._keywords;
}
set
{
this._keywords = value;
}
}
public string Comments
{
get
{
return this._comments;
}
set
{
this._comments = value;
}
}
}
Join me on Facebook
Anyway, Array, author, BindingFlags, Bytes, Close, Collections, Comments, ConstructorInfo, Convert, CreatePropertyItem, FileMode, filepath, FileStream, FromStream, Generic, GetBytes, GetConstructor, Image, ImageMetadata, imagePropertyItems, instance, Keywords, Length, Metadata, NonPublic, Open, PropertyItem, PropertyItems, propertyValue, Public, Read, ReadEXIFMetadata, Reflection, Save, SaveEXIFMetadata, SetPropertyItem, snippet, solution, System, Text, Title, Type, Unicode, Value, Write, _author, _comments, _keywords, _title
Leave a comment