The following code illustrates the problem I am faced with. If I load a CR2 file with
var format = FREE_IMAGE_FORMAT.FIF_RAW;
retVal = FreeImage.LoadBitmap("AJ2A1447.cr2", ref format);
then I successfully load the RAW file. If I use something like
using (Stream stream = new FileStream("AJ2A1447.cr2", FileMode.Open, FileAccess.Read))
{
var format = FREE_IMAGE_FORMAT.FIF_RAW;
freeImageHandle = FreeImage.LoadFromStream(stream, ref format);
if (freeImageHandle.IsNull)
{
throw new Exception("Unable to load image from stream");
}
retVal = FreeImage.GetBitmap(freeImageHandle);
}
then I am unsuccessful as freeImageHandle is null. I use FileStream for a test, the real code will use a MemoryStream.
Any clue to why LoadFromStream fails?
there is number of RAW formats and I doubt if FREE_IMAGE_FORMAT.FIF_RAW knows how to decode CR2.
http://en.wikipedia.org/wiki/Raw_image_format
Try to use windows generated bitmap and jpg to see if your code works.
FreeImage uses libRawLite to read Canon CR2 raw format.
However, libRawLite does not support the sRAW CR2 files.
Related
I have this method for resizing images, and I have managed to input all of the metadata into the new image except for the XMP data. Now, I can only find topics on how manage the XMP part in C++ but I need it in C#. The closest I've gotten is the xmp-sharp project which is based on some old port of Adobe's SDK, but I can't get that working for me. The MetaDataExtractor project gives me the same results - that is, file format/encoding not supported. I've tried this with .jpg, .png and .tif files.
Is there no good way of reading and writing XMP in C#?
Here is my code if it's of any help (omitting all irrelevant parts):
public Task<Stream> Resize(Size size, Stream image)
{
using (var bitmap = Image.FromStream(image))
{
var newSize = new Size(size.Width, size.Height);
var ms = new MemoryStream();
using (var bmPhoto = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format24bppRgb))
{
// This saves all metadata except XMP
foreach (var id in bitmap.PropertyIdList)
bmPhoto.SetPropertyItem(bitmap.GetPropertyItem(id));
// Trying to use xmp-sharp for the XMP part
try
{
IXmpMeta xmp = XmpMetaFactory.Parse(image);
}
catch (XmpException e)
{
// Here, I always get "Unsupported Encoding, XML parsing failure"
}
// Trying to use MetadataExtractor for the XMP part
try
{
var xmpDirs = ImageMetadataReader.ReadMetadata(image).Where(d => d.Name == "XMP");
}
catch (Exception e)
{
// Here, I always get "File format is not supported"
}
// more code to modify image and save to stream
}
ms.Position = 0;
return Task.FromResult<Stream>(ms);
}
}
The reason you get "File format is not supported" is because you already consumed the image from the stream when you called Image.FromStream(image) in the first few lines.
If you don't do that, you should find that you can read out the XMP just fine.
var xmp = ImageMetadataReader.ReadMetadata(stream).OfType<XmpDirectory().FirstOrDefault();
If your stream is seekable, you might be able to seek back to the origin (using the Seek method, or by setting Position to zero.)
I writing a program that it can read .Dex file (Dexis X-ray image file) and convert it to jpg image. but i can't find out how to decode it.
i use this code to read and convert but the image is corrupt.
Read Image:
public static byte[] ImageToByte(string IMG_PATH)
{
byte[] img = null;
try
{
FileStream IM_STREAM = new FileStream(IMG_PATH, FileMode.Open, FileAccess.Read);
BinaryReader IM_BNR = new BinaryReader(IM_STREAM);
img = IM_BNR.ReadBytes((int)IM_STREAM.Length);
IM_BNR.Close();
IM_STREAM.Close();
}
catch (Exception ex)
{
StreamWriter swr = new StreamWriter("LOG.txt", true, Encoding.UTF8);
swr.WriteLine(ex.Message);
swr.Close();
}
return img;
}
Convert Image:
public static void SaveToFile(string path, byte[] b)
{
MemoryStream ms = new MemoryStream(b);
Image img = Image.FromStream(ms);
img.Save(path + "\\exam.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
img.Dispose();
}
The image before convert (.Dex, size 800x600px) -> after convert (.jpg, size 80x60). plz help me.
.dex is a semi-proprietary format. Using standard image decoding libraries the result you are seeing is the best you can do. If you are looking for a paid solution I know of a team that is currently working on a web services API for this but it hasn't been released publicly yet. If you'd be interested in being an early tester I can put you in touch.
I have function name uploadLayerIcons which is as follows:
private void uploadLayerIcon(string LayerName)
{
Bitmap icon= new Bitmap(#"C:\Users\HP\Desktop\911\Prism\Prism_Resources\m.png");
System.IO.MemoryStream stream = new System.IO.MemoryStream();
icon.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] imageBytes = stream.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
HttpWebRequest m_ObjRequest; //Request which needed to be sent to server
HttpWebResponse m_ObjResponse; // Response which is sent back from the server to the client
StreamReader reader = null; // making a stream reader to read the web pageand initialize it to null
string m_Url = "http://192.168.1.30/muneem/erp/uploadIcon.php" + "?bitmap=" + base64String + "&layerName=" + LayerName; // the url of that web page
string m_Response = "";
m_ObjRequest = (HttpWebRequest)WebRequest.Create(m_Url); // creating the url and setting the values
m_ObjRequest.Method = "GET";
m_ObjRequest.ContentType = "application/json; charset=utf-8";
//m_ObjRequest.ContentLength = 500;
m_ObjRequest.KeepAlive = false;
m_ObjResponse = (HttpWebResponse)m_ObjRequest.GetResponse(); // getting response from the server
using (reader = new StreamReader(m_ObjResponse.GetResponseStream())) // using stream reader to read the web page
{
m_Response = reader.ReadToEnd();
reader.Close(); // Close the StreamReader
}
m_ObjResponse.Close();
m_ObjRequest = null;
m_ObjResponse = null;
}
UploadIcon.php file is as follows:
<?php
$bitmap=$_GET['bitmap'];
$name=$_GET['layerName'];
$data = base64_decode($bitmap);
$filepath="app/uams/uploadedImages/".$name.".jpg";
file_put_contents($filepath,$data);
?>
Its not converting correctly the same image which i have sent to server.
I have search on internet many thing but all in vain. I have also tried this thing
Bitmap icon= new Bitmap(#"C:\Users\HP\Desktop\911\Prism\Prism_Resources\m.png");
icon.save("Path of srrver")
But its not working.
So, you are doing it pretty much wrong. First of all, if you change the extension of the file to .jpg it does not automagically become jpg image.
So, what I suggest you to do is to send the raw png data instead of bitmap, and then using something like this in php:
<?
$imagedata = $_POST["data"];
$im = imagecreatefromstring($imagedata);
$filepath="app/uams/uploadedImages/image.jpg";
imagejpeg($im,$filepath);
?>
Also, as pointed out in previous answer by #DoXicK, do not send file by GET method, you should post it instead, and that is what this example is based on.
PHP's function imagecreatefromstring identifies the image type, and creates the gdlib object accordingly (but it does not work very well with bitmaps). That is why I suggested that you use raw png data instead of converting it to bitmap. Also, bitmap data is unneccesary large for transfer.
For imagecreatefromstring to work you need GD Library installed and enabled. To see if it is enabled create an empty file (named for example info.php) and inside it put only
<?
phpinfo();
?>
If you see GD Support set to Enable on the page, when you open the file, you have gdlib enabled. If you do not see it, do the following:
On windows find ;extension=php_gd2.dll in php.ini file of your php installation, and uncomment it (remove ; from the beginning) so it now is extension=php_gd2.dll and then restart Apache.
On linux you need to do sudo apt-get install php5-gd and then restart Apache.
you are loading a PNG to BMP file format
You are sending a file by GET
you are saving the BMP file as JPG te minute you receive the BMP
So:
Don't open as PNG as BMP. open a PNG as PNG as it is either smaller or the same size. There is no need for the BMP here...
POST it
Just because you call it a JPG, doesn't make it a JPG. It currently is a BMP, saved to a JPG.
IF it even saves a .jpg file, it is a .bmp file with the wrong extension.
Im loading an image from a SQL CE db and then trying to load that into a PictureBox.
I am saving the image like this:
if (ofd.ShowDialog() == DialogResult.OK)
{
picArtwork.ImageLocation = ofd.FileName;
using (System.IO.FileStream fs = new System.IO.FileStream(ofd.FileName, System.IO.FileMode.Open))
{
byte[] imageAsBytes = new byte[fs.Length];
fs.Read(imageAsBytes, 0, imageAsBytes.Length);
thisItem.Artwork = imageAsBytes;
fs.Close();
}
}
and then saving to the Db using LINQ To SQL.
I load the image back like so:
using (FileStream fs = new FileStream(#"C:\Temp\img.jpg", FileMode.CreateNew ,FileAccess.Write ))
{
byte[] img = (byte[])encoding.GetBytes(ThisFilm.Artwork.ToString());
fs.Write(img, 0, img.Length);
}
but am getting an OutOfMemoryException. I have read that this is a slight red herring and that there is probably something wrong with the filetype, but i cant figure what.
Any ideas?
Thanks
picArtwork.Image = System.Drawing.Bitmap.FromFile(#"C:\Temp\img.jpg");
Based on the code you provided it seems like you are treating the image as a string, it might be that data is being lost with the conversion from byte[] to string and string to byte[].
I am not familiar with SQL CE, but if you can you should consider treating the data as a byte[] and not encoding to and from string.
I base my assumption in this line of code
byte[] img = (byte[])encoding.GetBytes(ThisFilm.Artwork.ToString());
The GDI has the bad behavior of throwing an OOM exception whenever it is not capable of understanding a certain image format. Use Irfanview to see what kind of image that really is, it is likely GDI can't handle it.
My advice would be to not use a FileStream to load images unless you need access to the raw bytes. Instead, use the static methods provided in Bitmap or Image objects:
Image img = Image.FromFile(#"c:\temp\img.jpg")
Bitmap bmp = Bitmap.FromFile(#"c:\temp\img.jpg")
To save the file use .Save method of the Image or Bitmap object:
img.Save(#"c:\temp\img.jpg")
bmp.Save(#"c:\temp\img.jpg")
Of course we don't know what type ArtWork is. Would you care to share that information with us?
As the title mentioned, I want to encode a Image Obj into some kind of text data (compact framework not support binaryformatter, correct me if I'm wrong). So is there any way to encode a Image Obj into text data and keep it in a XML file for being able to decode from XML file to Image obj later?
UPDATE: Here is what I did following Sam's respose. Thanks Sam!
//Write to XML
byte[] Ret;
using (MemoryStream ms = new MemoryStream())
{
myImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
Ret = ms.ToArray();
}
StreamWriter myWrite = new StreamWriter(myPathFile);
myWrite.Write(Convert.ToBase64String(Ret));
myWrite.Flush();
myWrite.Close();
Then when I want to decode Image from Base64String to Image:
StreamReader StrR = new StreamReader(myPathFile);
BArr = Convert.FromBase64String(StrR.ReadToEnd());
using (MemoryStream ms = new MemoryStream(BArr,0,BArr.Length))
{
ms.Write(BArr, 0, BArr.Length);
listControl1.BGImage = new Bitmap(ms);
}
Typically binary data is converted to Base64 when included in XML. Look at Convert.ToBase64String.