AVIReader - taking too long to save frames - c#

I am developing a program to grab images from four cameras and turn them into one picture only in style quad, 4 images in one. And it generate a .avi
AVIReader reader = new AVIReader();
List<byte[]> ImagemMainb = new List<byte[]>();
reader.Open(_rootPath + Path.GetFileName(_arqsCam01[i]));
while (reader.Position - reader.Start < reader.Length)
{
Bitmap aux = reader.GetNextFrame();
Bitmap r = new Bitmap(aux.Width * 2, aux.Height * 2, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
using (var g = Graphics.FromImage(r))
{
g.DrawImage(aux, new Rectangle(0, 0, aux.Width, aux.Height));
ImagemMainb.Add(ImageToByte(r));
}
}
reader.Close();
reader.Dispose();
And here is the method ImageToByte
public static byte[] ImageToByte(Image img)
{
byte[] byteArray = new byte[0];
using (MemoryStream stream = new MemoryStream())
{
img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
stream.Close();
byteArray = stream.ToArray();
}
return byteArray;
}
Using these codes takes too long to finish the process!
When I have a list of 84000 bitmaps in that case are 280 videos with frame rate = 5, size = 320x240, it takes forever.
Would have any problem in this code or have a better way?

i found the answer.
AVIReader reader = new AVIReader();
List<Bitmap> ImagemMain = new List<byte[]>();
reader.Open(_rootPath + Path.GetFileName(_arqs[0]));
while (reader.Position - reader.Start < reader.Length)
{
using (var aux = reader.GetNextFrame())
{
using (var r = new Bitmap(640, 480))
{
using (var g = Graphics.FromImage(r))
{
g.DrawImage(aux, new Rectangle(0, 0, aux.Width, aux.Height));
ImagemMain.Add((Bitmap)r.Clone());
}
}
}
}
Every video uploaded AVIWriter I open the file .avi and add bitmap.
With this is much more fast and does not take up almost no memory.

Related

Convert ogg audio file to opus audio file

I am recording ogg file in Html5. It is recording fine. But i want to convert OGG file OPUS format file. I have tried so many libraries which is not working as expected.
The following code returning error like below,
The frame size must be one of the following: 2.5, 5, 10, 20, 40 or 60.
Parameter name: length.
using (FileStream fileIn = new FileStream(#"C:\Users\Downloads\1.ogg", FileMode.Open))
using (MemoryStream pcmStream = new MemoryStream())
{
short[] packets = new short[0];
var decoder = Concentus.Structs.OpusDecoder.Create(48000, 2);
var oggIn = new Concentus.Oggfile.OpusOggReadStream(decoder, fileIn);
while (oggIn.HasNextPacket)
{
short[] packet = oggIn.DecodeNextPacket();
if (packet != null)
{
for (int i = 0; i < packet.Length; i++)
{
var oggbytes = BitConverter.GetBytes(packet[i]);
pcmStream.Write(bytes, 0, bytes.Length);
}
if (packets != null && packets.Length > 0)
Combine(packets, packet);
else
{
packets = new short[packet.Length];
packets = packet;
}
}
}
pcmStream.Position = 0;
using (var memoryStream = new MemoryStream())
{
pcmStream.CopyTo(memoryStream);
var encoder = new OpusDotNet.OpusEncoder(OpusDotNet.Application.Audio, 48000, 2);
opbytes = new byte[packets.Length];
var obytes = encoder.Encode(memoryStream.ToArray(), packets.Length, out int encodedLength);
System.IO.File.WriteAllBytes(#"C:\Users\Downloads\new.opus", memoryStream.ToArray());
}
}
Please help me to convert OGG audio file to OPUS audio file in c#.
Thanks in advance,
Mani

Unable to read QR using Zxing

I am using zxing library to generate and decode the QR codes. I my application I am generating QR code dynamically and sending the file containing QR by fax API. If I get this fax message from the api and decode it, Qr code is read successfully, but when I send a scanned copy of this file by fax and then receive and read it I am unable to do that. But if I try to read this file using my mobile Qr application it properly reads the Qr code. I am unable to find a solution how to read this file.
Methods used for encoding:
public static System.Drawing.Image GenerateJSONQrCode(QRJsonFax model)
{
var jsonString = JsonConvert.SerializeObject(model);
//encrypt json string
jsonString = Hugo.BLL.Utilities.EncryptionHelper.EncryptQR(jsonString, FaxSetting.IsUseHashing);
var bw = new ZXing.BarcodeWriter();
var encOptions = new ZXing.Common.EncodingOptions() { Width = 200, Height = 200, Margin = 0 };
bw.Options = encOptions;
bw.Format = ZXing.BarcodeFormat.QR_CODE;
var image = new Bitmap(bw.Write(Compress(jsonString)));
return image;
}
private static string Compress(string text)
{
byte[] buffer = Encoding.UTF8.GetBytes(text);
var ms = new MemoryStream();
using (var zip = new GZipStream(ms, CompressionMode.Compress, true))
{
zip.Write(buffer, 0, buffer.Length);
}
ms.Position = 0;
byte[] compressed = new byte[ms.Length];
ms.Read(compressed, 0, compressed.Length);
byte[] gzBuffer = new byte[compressed.Length + 4];
System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
return Convert.ToBase64String(gzBuffer);
}
Methods used for encoding and decoding
public static FaxReceiver.QrFinder DecodeQrCode(string imagePathToDecode)
{
long userId = 0;
Bitmap bitmapImage = (Bitmap)Image.FromFile(imagePathToDecode);
ZXing.BarcodeReader barcodeReader = new BarcodeReader() { AutoRotate = true, TryHarder = true }; ;
Result decode = barcodeReader.Decode(bitmapImage);
var scanResult = string.Empty;
if (decode != null)
{
scanResult= Decompress(decode.Text);
}
if (!string.IsNullOrWhiteSpace(scanResult))
{
//decrypt Qr received
var decryptedString = DecryptionHelper.Decrypt(scanResult, FaxSetting.IsUseHashing);
//deserialize JSON received
var resultJson = JsonConvert.DeserializeObject<QRJsonFax>(decryptedString);
if (resultJson != null)
{
long.TryParse(resultJson.UserID.ToString(), out userId);
return new QrFinder()
{
FilePath = imagePathToDecode,
UserId = userId,
PageNo = 0,
DataSourceID = resultJson.DataSourceID,
InboundFaxTypeID = resultJson.InboundFaxTypeID
};
}
}
return null;
}
private static string Decompress(string compressedText)
{
byte[] gzBuffer = Convert.FromBase64String(compressedText);
using (var ms = new MemoryStream())
{
int msgLength = BitConverter.ToInt32(gzBuffer, 0);
ms.Write(gzBuffer, 4, gzBuffer.Length - 4);
byte[] buffer = new byte[msgLength];
ms.Position = 0;
using (var zip = new GZipStream(ms, CompressionMode.Decompress))
{
zip.Read(buffer, 0, buffer.Length);
}
return Encoding.UTF8.GetString(buffer);
}
}
File containing Qr code
The problem is that the QR Decoder is getting confused by the gaps between the pixels in your faxed image. If we zoom into a corner of it, this is what we see.
The scanner is looking for solid black squares to identify the QR code.
If we shrink the image by 50%, it becomes readable.
See for yourself at http://zxing.org/w/decode?u=http%3A%2F%2Fi.stack.imgur.com%2FSCYsd.png
I would suggest that after receiving the faxed image, you should either shrink it, or apply a filter to ensure that the QR codes are solid black. You could also look at sending it at a smaller resolution to see if that helps.

WPF Returing Bitmap Image to browser - Self hosted Owin Application

I am working on a Self Hosted WPF Application (using Owin) that returns bitmap images to the browser.
My controller code looks like this:
public ImageSource GetmbTiles(string FILE, string Z, string X, string Y)
{
string mbtiles = string.Format(("C:\\{0}.mbtiles"), FILE);
string connString = string.Format("Data Source={0}", mbtiles);
using (SQLiteConnection conn = new SQLiteConnection(connString))
{
System.Text.StringBuilder Query = new System.Text.StringBuilder();
Query.Append("SELECT tile_data ");
Query.Append("FROM tiles ");
Query.Append(string.Format("where zoom_level={0} and tile_column={1} and tile_row={2} ", Z, X, Y));
using (SQLiteCommand cmd = new SQLiteCommand(Query.ToString(), conn))
{
conn.Open();
using (SQLiteDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
buffer = GetBytes(dr);
}
}
}
}
//return new System.IO.MemoryStream(buffer);
return byteArrayToImage(buffer);
}
private static BitmapImage byteArrayToImage(byte[] imageData)
{
if (imageData == null || imageData.Length == 0) return null;
var image = new BitmapImage();
using (var mem = new MemoryStream(imageData))
{
mem.Position = 0;
image.BeginInit();
image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = null;
image.StreamSource = mem;
image.EndInit();
}
image.Freeze();
return image;
}
private static byte[] GetBytes(SQLiteDataReader reader)
{
const int CHUNK_SIZE = 2 * 1024;
byte[] buffer = new byte[CHUNK_SIZE];
long bytesRead = 0;
long fieldOffset = 0;
using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
{
bytesRead = reader.GetBytes(0, fieldOffset, buffer, 0, buffer.Length);
while (bytesRead == buffer.Length)
{
stream.Write(buffer, 0, Convert.ToInt32(bytesRead));
fieldOffset += bytesRead;
bytesRead = reader.GetBytes(0, fieldOffset, buffer, 0, buffer.Length);
}
stream.Write(buffer, 0, Convert.ToInt32(bytesRead));
return stream.ToArray();
}
}
When I call this controller from my browser I only get a json file and not the image.
The exception Message is
<ExceptionMessage>Type 'System.IO.MemoryStream' with data contract name 'MemoryStream:http://schemas.datacontract.org/2004/07/System.IO' is not expected. Consider using a DataContractResolver if you are using DataContractSerializer or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to the serializer.</ExceptionMessage>
I am web developer very new to the world of WPF so pardon this noob question. But whatever I try to return the image so far isnt helping. I can see that the byte array is being populated. But the Byte Array wont display in a browser, is there some conversion that I am missing ? Any hint or help will be highly appreciated.
I am posting this solution for anyone else who may be in the same scenario, OWIN Self Hosted App that serves images or other files.
I resolved this by adding this to the controller method
Image img = byteArrayToImage(buffer);
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(ms.ToArray());
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
return result;
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}

Changing image size from stream

I've searched here for help with this, but nothing quite matches what I need. I have an image that gets uploaded, and I'd like to change the size before it gets saved to azure.
So currently my code is:
public ActionResult UserDetails(HttpPostedFileBase photo)
{ var inputFile = new Photo()
{
FileName = photo.FileName,
Data = () => photo.InputStream
};
//then I save to Azure
How would I change the photo.InputStream to 100x 100 px for example?
Here is how I do it:
byte[] imageBytes;
//Of course image bytes is set to the bytearray of your image
using (MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
{
using (Image img = Image.FromStream(ms))
{
int h = 100;
int w = 100;
using (Bitmap b = new Bitmap(img, new Size(w,h)))
{
using (MemoryStream ms2 = new MemoryStream())
{
b.Save(ms2, System.Drawing.Imaging.ImageFormat.Jpeg);
imageBytes = ms2.ToArray();
}
}
}
}
From there, I use a MemoryStream to upload. I use blob storage and use the UploadFromStreamAsync to load to blob.
This is a basic view of it.

wp8 Operation not permitted on IsolatedStorageFileStream

I am copying all images from my device to directory. While copying the images I am getting this error Operation not permitted on IsolatedStorageFileStream.
Here is my code to copy the files.
MediaLibrary m = new MediaLibrary();
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (store.DirectoryExists("ImagesZipFolder"))
{
deleteFileFolder("ImagesZipFolder");
}
if (!store.DirectoryExists("ImagesZipFolder"))
{
store.CreateDirectory("ImagesZipFolder");
foreach (var picture in m.Pictures)
{
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(#"ImagesZipFolder/" + picture.Name, FileMode.CreateNew, store))
{
BitmapImage image = new BitmapImage();
image.SetSource(picture.GetImage());
byte[] bytes = ConvertToBytes(image);
stream.Write(bytes, 0, bytes.Length);
}
}
}
}
Here is my ConvertToBytes method.
public byte[] ConvertToBytes(BitmapImage bitmapImage)
{
byte[] data = null;
WriteableBitmap wBitmap = null;
using (MemoryStream stream = new MemoryStream())
{
wBitmap = new WriteableBitmap(bitmapImage);
wBitmap.SaveJpeg(stream, wBitmap.PixelWidth, wBitmap.PixelHeight, 0, 100);
stream.Seek(0, SeekOrigin.Begin);
//data = stream.GetBuffer();
data = stream.ToArray();
DisposeImage(bitmapImage);
return data;
}
}
Basically what I am trying is to create a zip file of all images. I have total 222 images in my device. So how can I solve this issue ? How can I create a zip of this images?
Most probably this is due to the concurrent access to the file
you can refer to the link:
Operation not permitted on IsolatedStorageFileStream. error
I checked your code and it seems to be working (providing there's no error in DisposeImage() method) There is no OperationNotPermittedException occuring. However, if there is error in your code, then it can only be because of deleteFileFolder("ImagesZipFolder") line. Can you give me the snippet so that I can study it further. I m posting the working code... I have replaced that method with simple predefined one--
MediaLibrary m = new MediaLibrary();
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (store.DirectoryExists("ImagesZipFolder"))
{
store.DeleteDirectory("ImagesZipFolder");
}
if (!store.DirectoryExists("ImagesZipFolder"))
{
store.CreateDirectory("ImagesZipFolder");
foreach (var picture in m.Pictures)
{
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(#"ImagesZipFolder/" + picture.Name, FileMode.CreateNew, store))
{
BitmapImage image = new BitmapImage();
image.SetSource(picture.GetImage());
byte[] bytes = ConvertToBytes(image);
stream.Write(bytes, 0, bytes.Length);
}
}
}
}

Categories

Resources