c# - Convert a byte[] to Image without using a MemoryStream -
i having problem exporting sql images files. first initialize list. myrecord class graphicname, , graphic properties. when try go through list , save myrecord.graphic disk first chance exception of type 'system.objectdisposedexception'. realize because when converted bytes database image used using statement memorystream. can not use using statement , works, worried memory usage / memory leaks on 6,000 records. there way convert bytes image or there better design this?
... prior code using (sqldatareader reader = sqlcommand.executereader()) { while (reader.read()) { myrecord record = new myrecord(); record.graphicid = reader["graphic_id"].tostring(); record.graphic = !reader.isdbnull(reader.getordinal("image")) ? getimage((byte[])reader["image"]) : null; records.add(record); } ... more code private image getimage(byte[] rawimage) { using (system.io.memorystream ms = new system.io.memorystream(rawimage)) { image image = image.fromstream(ms); return image; } }
you shouldn't use using
statement stream passed image.fromstream
, image
class responsible stream on. documentation:
you must keep stream open lifetime of image.
just change code to:
private image getimage(byte[] rawimage) { var stream = new memorystream(rawimage); return image.fromstream(stream); }
... make sure dispose of image
objects later. dispose of stream, allowing memory garbage collected. there shouldn't memory leaks - need work out whether can load 6000 images memory @ time anyway.
(if don't dispose of image
objects, they're finalized anyway @ point - better dispose of them deterministically.)
Comments
Post a Comment