I have copied some data in Clipboard using MS-Word Com API
Range.CopyAsPicture();
and when I am pasting(Ctrl + v) it on window's paint software its getting displayed.
Issue is while converting Clipboard data to image Using c#
I looked into various link on internet and tried following code which is not working
MemoryStream ms = Clipboard.GetData("DeviceIndependentBitmap") as MemoryStream;
above line returning null
clipboardData.GetDataPresent(System.Windows.Forms.DataFormats.Bitmap)
Above line returning false
Can anyone please suggest how can convert the clipboard data to image.
If all you are looking for is getting the bitmap of the image in the clipboard (or the underlying binary data), look into using GetImage.
Here is a code snippet you can try:
BitmapSource bmpSource = Clipboard.GetImage();
MemoryStream ms = new MemoryStream();
BitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmpSource));
encoder.Save(ms);
ms.Seek(0, SeekOrigin.Begin);
In case that also doesn't seem to work, you can try looking into this workaround, it doesn't seem directly related, but it might be just what you need.
Apparently MS Office puts images on the clipboard as a stream of PNG bytes, which is actually a really sensible innovation. This image data simply uses the identifier "PNG".
So try this instead:
if (retrievedData.GetDataPresent("PNG"))
{
MemoryStream png_stream = retrievedData.GetData("PNG") as MemoryStream;
if (png_stream != null)
return new Bitmap(png_stream);
}
Related
I did see "PDF to Image using GhostScript. No image file has to be created", but that only (sort of) answered half my question. Is it possible to use GhostScriptSharp (or the regular GhostScript dll) to convert a pdf in a MemoryStream to a jpg in a MemoryStream? I speak of a dynamically filled in pdf form with iTextSharp which I am already directing to a MemoryStream to save to a database or stream to a http response, and I'd really love to avoid saving to a file (and subsequent cleanup) if I can.
The sole answer in the answer I referenced claimed that one has to go down to the GhostScript dll to do the latter part, but it was obvious I would need to do a good bit of leg-work to figure out what that meant. Does anyone have a good resource that could help me on this journey?
The thing is that the PDF language, unlike the PostScript language, inherently requires random access to the file. If you provide PDF directly to Standard Input or via PIPE, Ghostscript will copy it to a temporary file before interpreting the PDF. So, there is no point of passing PDF as MemoryStream (or byte array) as it will anyway end up on the disk before it is interpreted.
Take a look at the Ghostscript.NET and it's GhostscriptRasterizer sample for the 'in-memory' output.
Ghostscript.Net is a wrapper to the Ghostscript dll. It now can take a stream object and can return an image that can be saved to an stream. Here is an example that I used on as ASP page to generate PDF's from a memory stream. I haven't completely figured out the best way to handle the ghostscript dll and where to locate it on the server.
void PDFToImage(MemoryStream inputMS, int dpi)
{
GhostscriptRasterizer rasterizer = null;
GhostscriptVersionInfo version = new GhostscriptVersionInfo(
new Version(0, 0, 0), #"C:\PathToDll\gsdll32.dll",
string.Empty, GhostscriptLicense.GPL);
using (rasterizer = new GhostscriptRasterizer())
{
rasterizer.Open(inputMS, version, false);
for (int i = 1; i <= rasterizer.PageCount; i++)
{
using (MemoryStream ms = new MemoryStream())
{
Image img = rasterizer.GetPage(dpi, dpi, i);
img.Save(ms, ImageFormat.Jpeg);
ms.Close();
AspImage newPage = new AspImage();
newPage.ImageUrl = "data:image/png;base64," + Convert.ToBase64String((byte[])ms.ToArray());
Document1Image.Controls.Add(newPage);
}
}
rasterizer.Close();
}
}
Overview of my application: On the client side, a series of snapshots are taken with a webcam. On submit, I want the images to be converted to a byte array, and have that byte array sent to a service I have written.
My problem: I'm trying to save a single image to a MemoryStream, but it continues to break, spitting out the message, "A generic error occured in GDI+." When I dig deeper, I see that the exception is thrown when the MemoryStream's buffer position is at 54. Unfortunately, it's a 1.2 mb photo. Here's the block of code:
// Create array of MemoryStreams
var imageStreams = new MemoryStream[SelectedImages.Count];
for (int i = 0; i < this.SelectedImages.Count; i++)
{
System.Drawing.Image image = BitmapFromSource(this.SelectedImages[i]);
imageStreams[i] = new MemoryStream();
image.Save(imageStreams[i], ImageFormat.Bmp); /* Error is thrown here! */
}
// Combine MemoryStreams into a single byte array (Threw this
// in in case somebody has a better approach)
byte[] bytes = new byte[imageStreams.Sum(s => s.Length)];
for(int i = 0; i < imageStreams.Length; i++)
{
bytes.Concat(imageStreams[i].ToArray());
}
And here is my BitmapFromSource method
// Converts a BitmapSource object to a Bitmap object
private System.Drawing.Image BitmapFromSource(BitmapSource source)
{
System.Drawing.Image bitmap;
using (MemoryStream ms = new MemoryStream())
{
BitmapEncoder encoder = new BmpBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(source));
encoder.Save(ms);
bitmap = new System.Drawing.Bitmap(ms);
}
return bitmap;
}
A lot of what I have read about the Generic GDI+ Error points to a permissions issue, but I don't see how that would apply here, considering I'm not saving to the file system. Also, I've seen that this error can arise due to the MemoryStream closing before the image is being saved, but I also don't see how this would apply considering I create the MemoryStream immediately before I save the image. Any insight would be greatly appreciated.
I think your problem actually lies in your BitmapFromSource method.
You're creating a stream, then creating a bitmap from that stream, then throwing the stream away, then trying to save the bitmap to another stream. However, the documentation for the Bitmap class says:
You must keep the stream open for the lifetime of the Bitmap.
By the time you come to save that bitmap, the bitmap is already corrupted because you've thrown the original stream away.
See: http://msdn.microsoft.com/en-us/library/z7ha67kw
To fix this (bearing in mind I've not written the code let alone tested it), create the MemoryStream inside the first for loop in your first block of code, and pass that memory stream to your BitmapFromSource method as a second parameter.
Please see SecurityException when calling Graphics.DrawImage which leads to Common Problems with rendering Bitmaps into ASP.NET OutputStream
I have one WPF application in which I am uploading autocad drawing files (.dwg), convert it to byte array and save to database. When I read back that file from byte array, I am getting following error :
No imaging component suitable to complete this operation was found.
My code to convert in byte array is below :
FileStream fs = new FileStream(dlg.FileName, FileMode.Open, FileAccess.Read);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, System.Convert.ToInt32(fs.Length));
fs.Close();
I am trying to get image from byte array using below code :
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.CreateOptions = BitmapCreateOptions.None;
bi.CacheOption = BitmapCacheOption.Default;
bi.StreamSource = new MemoryStream(data);
RenderOptions.SetBitmapScalingMode(bi, BitmapScalingMode.Linear);
bi.EndInit();
Above code works fine for other image files like jpg, png, bmp, gif. but not working for dwg file. Can anybody guide me what's wrong in my code ?
Thanks
Times ago I was searching for DWG library in C# and found this one:
http://www.woutware.com/cadlib.html, but after never used it.
You can not threat DWG files like ordinar image files, DWG is fairly complicated format for storing 2D and 3D data as well. And years ago also was a subject of frequent change and all licensing mess.
Hope this helps.
You have answered it yourself!
Above code works fine for other image files like jpg, png, bmp, gif.
but not working for dwg file.
For this to work correctly deserialise the byte array back to as "dwg file" itself and use some APIs to convert it to a bitmap and use that as the image source.
Try using a type converter
FileStream fs = new FileStream(dlg.FileName, FileMode.Open, FileAccess.Read);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, System.Convert.ToInt32(fs.Length));
fs.Close();
TypeConverter tc = TypeDescriptor.GetConverter(typeof(BitmapImage));
BitmapImage bitmap1 = (BitmapImage)tc.ConvertFrom(data);
Try using strm.Seek(0, SeekOrigin.Begin); because it may be possible you must have gone past through the stream with read
One option is to use http://www.opendwg.org/
Although not free, it is non-profit.
But it will only parse the dwg file for you into collection of lines, circles, polygons etc.
You still need to piece together and render the image.
I have a functioning application in c#/.net that currently accepts raw image data in a bayer format from a set of embedded cameras and converts them to jpeg images. To save transmission time, I have modified the embedded devices to encode the images as jpegs prior to transmission. I'm an experienced embedded programmer but a total c#/.net noob. I have managed to modify the application to save the arrays to file with a jpeg name using this snippet: ( the offset of 5 is to skip header data in the transmission frame)
FileStream stream = File.Create(fileName);
BinaryWriter writer = new BinaryWriter(stream);
writer.Write(multiBuff.msgData, 5, multiBuff.dataSize - 5);
writer.Close();
The files open up fine, but now I want to treat the data as a bitmap without having to save & load from file. I tried the following on the data array:
MemoryStream stream = new MemoryStream(data);
BinaryReader reader = new BinaryReader(stream);
byte[] headerData = reader.ReadBytes(5);
Bitmap bmpImage = new Bitmap(stream);
But this throws a parameter not valid exception. As a newbie, I'm a little overwhelmed with all the classes and methods for images and it seems like what I'm doing should be commonplace, but I can't find any examples in the usual places. Any ideas?
I think you are looking for Bitmap.FromStream() :
Bitmap bmpImage = (Bitmap)Bitmap.FromStream(stream);
Actually using new Bitmap(stream) should have worked as well - this means that the data in the stream does not constitute a valid image - are you sure the jpg is valid? Can you save it to disk and open it i.e. in Paint to test?
You use the Image class.
Image image;
using (MemoryStream stream = new MemoryStream(data))
{
image = Image.FromStream(stream);
}
FYI it didn't work because reader.ReadBytes(5) returns the 5 first bytes of stream not the bytes after position 5
I display images in my WPF app using BitmapImage.
However, I would like an easy way to save these (as JPG) to a different location (ideally into a Stream or object that can be passed around).
Is it possible using BitmapImage or do I have to use other means? If so what other means are there for either loading an Image and saving as JPG or converting a BitmapImage into this element to then save off?
Thanks
Something like:
public byte[] GetJPGFromImageControl(BitmapImage imageC)
{
MemoryStream memStream = new MemoryStream();
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(imageC));
encoder.Save(memStream);
return memStream.GetBuffer();
}
(from: WPF Image to byte[])