I have a bit of code that I have been working with to capture an image from a VideoCaptureElement from WPFMediaKit. it works great!
bmp.Render(videoElement);
BitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmp));
string now = DateTime.Now.Year + "" + DateTime.Now.Month + "" + DateTime.Now.Day + "" + DateTime.Now.Hour + "" + DateTime.Now.Minute + "" + DateTime.Now.Second;
string filename = now + "pic.jpg";
FileStream fstream = new FileStream(filename, FileMode.Open);
encoder.Save(fstream);
fstream.Close();
The problem I am facing though is that I need to get a byte[] data now rather than save a file. Currently I am doing this with a open filedialog box and a filestream:
if (File.Exists(FileLocation))
{
//Retreave image from file and binary it to Object image
using (FileStream stream = File.Open(FileLocation, FileMode.Open))
{
BinaryReader br = new BinaryReader(stream);
byte[] data = br.ReadBytes(maxImageSize);
image = new Image(dlg.SafeFileName, data, fileSize);
}
}
What I'd like to do is to take the capture and rather than save a file, I'd like to get it as a byte[] type. Is there a way to convert either RenderTargetBitmap or BitmapEncoder to a byre[] array? Or possibly I'm thinking to convert those to a memory stream so a binary reader can use it?
thanks!
To convert an BitmapSource to a byte array you can do something like this,
Where bmp is your BitmapSource or RenderTargetBitmap.
BitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmp));
byte[] arr = null;
using (MemoryStream memStream = new MemoryStream())
{
encoder.Save(memStream);
arr = stream.ToArray();
}
In addition to the already mentioned saving to a stream in bmp format, you can also call CopyPixels on a BitmapSource.
That will give you the original pixels, in the original format, with no header.
See this msdn link
Related
I am trying to store MemoryStream into MagicImage, but when I am trying to upload file with heic format it still uploading with heic format, but it should upload it with jpeg format. So I kind of do not understand where I am doing wrong. So could someone help me? I am trying it open in Frame in web, but it does not open bc it is not converting it to jpeg.
using (MemoryStream ms = new MemoryStream())
{
create.PostedFile.InputStream.CopyTo(ms);
var data = ms.ToArray();
byte[] data1 = null;
using (var image = new MagickImage(data))
{
// Sets the output format to jpeg
image.Format = MagickFormat.Jpeg;
// Create byte array that contains a jpeg file
data1 = image.ToByteArray();
}
var file = new ClientFile
{
Data = data1, // here where it should store it in jpeg
};
While I have never used your way of writing the image, this is what I use in my implementations and it always works:
var image = new MagickImage(sourceStream);
var format = MagickFormat.Jpg;
var stream = new MemoryStream();
image.Write(stream, format);
stream.Position = 0;
EDIT
If you don't add:
stream.Position = 0
sending the stream will not work as it will start saving from the current position which is at the end of the stream.
I have an Image I am retrieving from the database as a byte array. I want to save it outside the Project i.e on the Clients System. I would appreciate if the code aspect can be assisted with. Here is a sample method I have so far:
public Image byteArrayToImage2()
{
var filePath = "C:\\cat.jpg";
byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);
Image returnImage = null;
using (MemoryStream ms = new MemoryStream(fileBytes))
{
returnImage = Image.FromStream(ms);
returnImage.Save("cat2.jpg", ImageFormat.Jpeg);
}
return returnImage;
}
Try the below approach
PS: make sure your fileBytes is of type byte Array.
MemoryStream imageStream = new MemoryStream();
imageStream.Write(fileBytes, 0, fileBytes.Length);
// Include the file name along with extension (Eg: 'C:\TestImage.JPEG')
FileStream fs = File.Create("Give the path where you want to save the image");
imageStream.WriteTo(fs);
fs.Close();
imageStream.Close();
following is the code added:
The image object is in the library.imaging.
"using System.Drawing;"
"using System.Drawing.Imaging;"
{
byte[] b = Convert.FromBase64String("R0lGODlhAQABAIAAA");
Image image;
using (MemoryStream memstr = new MemoryStream(b))
{
image = Image.FromStream(memstr);
}
}
Here is the new code I'm working on:
{
string base64BinaryStr = " ";
byte[] PDFDecoded = Convert.FromBase64String(base64BinaryStr);
string FileName = (#"C:\Users\Downloads\PDF " + DateTime.Now.ToString("dd-MM-yyyy-hh-mm"));
BinaryWriter writer = new BinaryWriter(File.Create(FileName + ".pdf"));
writer.Write(PDFDecoded);
string s = Encoding.UTF8.GetString(PDFDecoded);
}
So this is your current code:
byte[] PDFDecoded = Convert.FromBase64String(base64BinaryStr);
string FileName = (#"C:\Users\Downloads\PDF " + DateTime.Now.ToString("dd-MM-yyyy-hh-mm"));
BinaryWriter writer = new BinaryWriter(File.Create(FileName + ".pdf"));
writer.Write(PDFDecoded);
You don't actually need BinaryWriter for this. File.Create already gives you a FileStream:
FileStream writer = File.Create(FileName + ".pdf");
writer.Write(PDFDecoded, 0, PDFDecoded.Length);
But this will still have the problem you're experiencing because you're not flushing the data to it. We also need to close the file. Thankfully, we can wrap it in using and it will do both for us:
using (FileStream writer = File.Create(FileName + ".pdf"))
{
writer.Write(PDFDecoded, 0, PDFDecoded.Length);
}
But a simpler way to do this is:
File.WriteAllBytes(FileName + ".pdf", PDFDecoded);
As for PDF -> Image, you'll probably have to see if there is a library available for this (search "PDF to Image NuGet") that can help you with this as I don't think there is anything built-in.
Just a thought, you don't need to create a physical PDF file, you can have it in memory and convert it to image from there.
Now the problem is that you cannot use Image from System.Drawing.Imaging for this, it doesn't support reading PDF file.
Instead you'll need to search for some library that can do that.
For example, try GemBox.Pdf, you can use it like this:
string base64String = "...";
byte[] pdfBytes = Convert.FromBase64String(base64String);
using (PdfDocument pdfDocument = PdfDocument.Load(new MemoryStream(pdfBytes)))
{
ImageSaveOptions imageOptions = new ImageSaveOptions(ImageSaveFormat.Png);
string imageName = DateTime.Now.ToString("dd-MM-yyyy-hh-mm") + ".png";
pdfDocument.Save(#"C:\Users\Downloads\" + imageName, imageOptions);
}
I've used the code provided on this Convert example.
I have a jpg strign stored in "(string)HttpContext.Current.Session["image" + 0];" that I am trying to convert to a System.Drawing.Image.
I know the string is correct, because when I do this -
img.Src = "data:image/jpg;base64," + (string)HttpContext.Current.Session["image" + 0];
Everying works as intended.
But when I do this -
string inputString = (string)HttpContext.Current.Session["image" + 0];
byte[] imageBytes = Convert.FromBase64String(inputString);
using (MemoryStream ms = new MemoryStream(imageBytes))
{
System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);
}
I get and error telling me the format is incorrect when trying to create an image from the stream.
Please help
don't you need to convert webp to jpg/png first?
for example WebP-wrapper
using (WebP webp = new WebP())
{
var image = webp.Decode(imageBytes );
}
I'm trying to develop API that returns a profile of employees including their pictures, the images are stored in SQL database as image data type
TypeConverter typeConverter = TypeDescriptor.GetConverter(typeof(Bitmap));
Bitmap bmp = (Bitmap)typeConverter.ConvertFrom(Emp.img);
//3
var Fs = new FileStream(HostingEnvironment.MapPath("~/Images") + #"\I" + id.ToString() + ".png", FileMode.Create);
bmp.Save(Fs, ImageFormat.Png);
bmp.Dispose();
//4
Image img = Image.FromStream(Fs);
Fs.Close();
Fs.Dispose();
//5
MemoryStream ms = new MemoryStream();
img.Save(ms, ImageFormat.Png);
//6
response.Content = new ByteArrayContent(ms.ToArray());
ms.Close();
ms.Dispose();
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
response.StatusCode = HttpStatusCode.OK;
return response;
}
I want to use this API in Android Studio where I have to convert the image data type to string or any other applicable data time with Volley.
I'll use a base64 representation of the image:
byte[] imageAsBytes = File.ReadAllBytes(#"your\path\to\image.png");
string imageAsString = Convert.ToBase64String(imageArray);
Then send it back to the Android Studio client and do the following:
byte[] imageAsStringInAndroidStudio = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
Just check if you have to strip the "data:image/jpg;base64" from the data before parsing it into Android Studio.