A DLL file contains some images inside PNG resource type.
I can view the PNG images in softwares like Resource Hacker, Anolis Resourcer & Resource Tuner. Check this screenshot of Anolis Resourcer for more details:
Can someone tell me how do I get the PNG image no. 5220 from the DLL file and put it inside a PictureBox? I don't think APIs like LoadImage or LoadBitmap will work.
// get the assembly containing the image
var assembly = Assembly.GetExecutingAssembly();
// set the picturebox image to read the embedded resource
pictureBox1.Image = Image.FromStream(
assembly.GetManifestResourceStream("AssemblyName.test.png")
);
where AssemblyName.test.png is the fully qualified name of the embedded resource inside the assembly.
UPDATE:
It seems that you are trying to extract resources from a native assembly. You may take a look at the following article which illustrates how this could be done using P/Invoke.
The link that Darin posted (which has consequently been marked as the answer) does not contain functional code. I've evaluated the code posted there (http://khason.net/blog/how-to-load-unmanaged-native-resources-from-managed-c-code/) and found that it does not work properly for any Bitmap image embedded in any win32 dll as a bitmap resource.
Additionally, Hans Passant leaves off a myriad of steps effectively rendering his post useless.
The only somewhat close solution that I've been able to find comes from an article written in 2004 for the XP Theme dll junk. You can find the 'GetResourcePNG' method in ThemeManager.cs here http://www.codeproject.com/KB/miscctrl/XPTaskBar.aspx
However, it should be noted that I've been having a lot of difficulty with this method, as the call to bitmap.RotateFlip(RotateFlipType.Rotate180FlipX); causes memory issues when trying to access pngs within authui.dll on my system
Update:
I've found the code listed here (http://www.vbaccelerator.com/home/NET/Code/Controls/Explorer_Bar/ExplorerBar_Control_Source_Code.asp) to be by far the most functional, produce the fewest errors and produces the fastest results. The code is written in c# even though the domain name would indicate otherwise. Using the two classes; ImageUtility and ResourceLibrary, you can easily pull a PNG out of a standard, non-.net resource library/dll:
public static Bitmap GetStandardResourceBitmap(String dllName, String resourceId) {
Bitmap result = null;
using (ResourceLibrary library = new ResourceLibrary() { Filename = dllName }) {
IntPtr hDib = library.GetResource(resourceId, ResourceLibrary.ImageType.IMAGE_BITMAP, ResourceLibrary.ImageLoadOptions.LR_CREATEDIBSECTION);
if (!hDib.Equals(IntPtr.Zero)) {
result = ImageUtility.DibToBitmap(hDib);
ImageUtility.DeleteObject(hDib);
}
}
return result;
}
I chose to have resourceId in my method a String, only because it doesn't require an overload and using numbered resource Ids is as simple as prepending a '#'.
GetStandardResourceBitmap("shell32.dll", "#632");
Cheers
A PNG image is not one of the standard Win32 resource types. It is usually embedded as a binary blob with the named resource type "PNG", although that's not guaranteed. By far the easiest way to figure this out is by opening the file with Visual Studio's File + Open + File command. You'll see the embedded resources organized in a tree, hopefully with a descriptive name, right-click a candidate and select Export to save it to disk.
Doing this programmatically requires a lot of gritty pinvoke. It is tricky because both the resource type and the resource ID can be either a string or an IntPtr so you'll need 4 overloads for FindResource. In order, you'll need LoadLibraryEx() to load the file without executing any of its code. FindResource to get a handle to the resource. SizeOfResource to know how large it is. LoadResource + LockResource to get a pointer to the resource data. Marshal.Copy() to copy the resource data into a byte[]. Clean up with FreeResource and FreeLibrary.
Related
I have an issue with a class library; I am preparing a library with an interface that represents a specific data storage signature. The purpose is to use the interface as a basis for implementing a number of specific classes storing configuration information in different formats (text files, xml files, etc.) while retaining the same usage profile to the application using it. I have a problem, though. In this case I am trying to embed an xml file as a resource - this file is one type of format to store configuration data. The file is located as an embedded resource in a subfolder to the project, as shown in the attached illustration.
In the following code snippet it is shown how I have implemented the functionality until now.
public ConfigInfoXmlSource()
{
if (!string.IsNullOrEmpty(Settings.Default.CurrentConfigFile))
FileNameAndPath = Settings.Default.CurrentConfigFile;
else
FileNameAndPath = DefaultConfigFileName + DefaultFileExtension;
// Prepare XML.
System.Reflection.Assembly a = Assembly.GetExecutingAssembly();
XmlDocument doc = new XmlDocument();
Stream manifestResourceStream =
a.GetManifestResourceStream("TestTool.Config.Config1.xml");
if (manifestResourceStream == null)
{
// ???
}
...
doc.Load(manifestResourceStream);
...
}
In the section marked "Prepare XML" I am trying to read a stream from the embedded resource. After the reading, it is tested whether a stream was indeed created. If the file is found, the manifestResourceStream will contain the xml data - so far so good. The problem arises if the file for some reason has been accidentally deleted - in that case I want to create a new file as an embedded resource to replace the deleted file. That is supposed to happen in the conditional in the part shown as "???".
I have tried everything I could think of, searched Google for answers, etc. - to no avail.
Does anyone have a clue to how this is accomplished? Any help will be greatly appreciated.
Thanks in advance.
Best regards.
If you have a embedded resource,it is built into your binaries.It is not an physical file,rather something which is present inside the built file(dll in this case).So,once it is included,I do not think it can ever be deleted. As per my knowledge embedded resource can only be set while building your project binaries and you can not explicitly do it at runtime as it is not needed due to reasons mentioned above.
Hey everyone just trying to make a program that browses video files and reads the title and description from the files metadata. I found some docs from microsoft here giving whats needed but how do I access these functions? what using namespaces are needed in c#? I would love any help that can be provided.
In that link you posted, scroll to the bottom and click "Shell Metadata Providers". There's more more information and some sample C++ code.
Here are some other relevant links:
Reading/Writing metadata of audio/video files
http://www.codeproject.com/Articles/14535/Accessing-WMF-metadata-with-C
https://social.msdn.microsoft.com/Forums/pt-BR/0f36a3b2-4d3d-4842-88a4-bea493bbbace/read-video-filemov-avi-mpg-etc-meta-data?forum=csharpgeneral
https://web.archive.org/web/20170225230114/https://stackoverflow.com/questions/7396265/c-sharp-to-read-properties-of-video-files
Sorry I can't give you anything more concrete, however it looks like some tag libraries (i.e. for reading MP3 metadata) may work as well, as the metadata for videos seems to be stored in a similar, if not identical, format. That being said, you can give TagLib# a shot.
https://www.nuget.org/packages/taglib/
I've made a simple C# code (portable to Unity, too) csatomreader. It's optimized for speed and can read the atoms over HTTP, too.
E.g. Get title:
using (FileStream stream = new FileStream(fileName, FileMode.Open))
{
var mp4Reader = new AtomReader(stream);
string value = mp4Reader.GetMetaAtomValue(AtomReader.TitleTypeName);
Console.WriteLine($"{atomTypeName}: {value}");
}
If you need to get more metadata values at once, then iterate over ParseAtoms(), e.g. see the GetMetaAtomValue() source.
We have some legacy code (console executable) that is called by our web application which has hard coded absolute paths to the file system for accessing certain files when it is run. This has limited our web application to a single instance per server. Is there any way to redirect a process/application's file access to a different folder (maybe a way to force it to use some virtual file system)?
For example: The executable may look for a file in "C:\inetpub\wwwroot\webappname\schemas". Can we force all references to that path to point to "C:\inetpub\wwwroot\webapp2\schemas" instead?
There might be two approaches. The first one is definitely easier.
By modifying the executable
If the application is written in .Net, use a decompiler like the one from 9Rays.Net, decompile the code, and make modifications. This might also work for Java.
If it's a native application, open the application in a hex editor, locate the string and change it. It has to keep the same length, however you can use a null terminal \0 to "shorten" it.
Using C#
Crate a launcher for the application, which gets called instead, and hooks into read/write calls to modify the paths. This can be done in C#, and you can find resources on the Internet for it.
Finally found an answer. I got it to work in .Net, I don't know if it will help for any other languages. Inspiration came from this blog: http://blog.didierstevens.com/2006/07/07/viewing-strings-in-executables/
I downloaded Mcaffee's BinText 3.03 (http://www.mcafee.com/us/downloads/free-tools/bintext.aspx), and ran it on my test EXE. I searched through the list, and found the string I wanted to replace. This gives you a file position offset. My string was at 0x73F according to BinText. The following code replaced the first two characters of my string with "AK". With a little rework, you could do actual string removal, instead of a simple 1:1 character replacement.
{
string file = "TrashV1.exe"; // Input EXE
string fileout = "TrashV2.exe";
File.Delete(fileout);
byte[] barr = File.ReadAllBytes(file);
int offset = 0x73e; // NOTE! This is one LESS than the offset that MCaffee reported!
string replace = "AK";
var enc = new System.Text.UnicodeEncoding();
byte[] unicode = enc.GetBytes(replace);
for (int i = 0; i < unicode.Length; i++)
{
barr[offset + i] = unicode[i];
}
File.WriteAllBytes(fileout, barr);
}
TrashV1.exe: STACK_OVERFLOW
TrashV2.exe: AKACK_OVERFLOW
I am working on Emgu cv as a console application and I was trying to load an jpeg format image file from computer disk.I have tried the following ways but nothing is working?
Image input = Image.FromFile("C://Users//...//Image.jpg");
Bitmap master = (Bitmap)input;
Image<Gray,byte> InputImage = new Image<Gray,byte>(master);
RecognizeFaces(InputImage);
And this way too
Image<Bgr,byte> inputImage = new Image<Bgr,byte>("C:\\Users\...\Image.jpeg");
Image<Gray,byte> grayFrame = inputImage.Convert<Gray,byte>();
Both ways Its not working.Any other option? It stops running here
_ptr = CvInvoke.cvCreateImageHeader(new Size(cols, rows), CvDepth, numberOfChannels);
in a class known to be Image.cs of Emgu cv.And it throws type initializer for 'Emgu.CV.CvInvoke' Exception.The File path is perfect/correct.the error looks like this.
The inner exception is "System.BadImageFormatException An attempt was made to load a program with an incorrect format Exception for hresult 0x8007000B." Configuration manager and build target are the same both any cpu.
http://www.mediafire.com/view/myfiles/#6557l4iwzpza7m5
Could you please tell me what i am doing wrong here? Thanks
Had the same problem. My solution was to change the target platform of the application to explicitly "x64". (I have a 64bit system and the 64bit libraries)
The delimiters in the file path are reversed for Windows. Did you try it like this "C:\Users\...\Image.jpeg"? (instead of "//")
You can check it with File.Exists to be sure.
I would look for mistakes like that (simple mistakes). Generally I don't remember having problems loading an image from file with Emgu.
I included an image as a resource following this post:
How to create and use resources in .NET
I am using PDFSharp library to create a PDF. The method to draw an image, requires the path of the image. How do I get the path of Properties.Resources.Image?
Or is there another way to do this?
The Properties.Resources.Image is in-memory resource.
You can save Image to temp file and the get the path.
var path = Path.GetTempPath();
Properties.Resources.logo.Save(path);
Above uses Bitmap.Save
You can actually create an image, without saving it, using XImage.FromGdiPlusImage():
var image = XImage.FromGdiPlusImage(Properties.Resources.logo);
As of PDFsharp/MigraDoc 1.50 beta 2 and newer you no longer need a path when using MigraDoc. It was already mentioned that PDFsharp does not need a filename, as images can be read from e.g. streams.
MigraDoc still requires a string. You encode the image data as a string (BASE64 format) and pass that string as a filename.
See also:
http://pdfsharp.net/wiki/MigraDoc_FilelessImages.ashx