Encoding of Bitmaps and arrays of bytes
Hello
I was hitting my head several times on my desk for a few days, trying to get my program if care, nothing will do. No other options, I decided that I would ask experts.
I'm doing a program that will ask the user to select an image, and then encode it to a binary string and store it in an XML file. He will then be able to "decode" the wire and rebuild.
I followed a few online guides, but I can't seem to get anything to work. My understanding is that I need to penetrate the BitmapData Bitmap from its components, to convert to a "byteArray" who is saved, (or possibly coded) then this byteArray of the data collected and transformed into a clip on the stage. However, no matter what I do, I can't seem to properly recreate the bitmap image, once I got the data... It throws always an "end of file".
In order to get the basics, I cut my code down to the bare minimum - what is just to load the image from the local file system, enter its bitmapdata, clone and place it in a new Bitmap that is added to the stage. However, I get only ever returned an error message "End of file encountered" - which seems to indicate, to me, is not properly populating the byteArray. (He looks certainly way too short when the trace)
Help, please!
Here is my code for the base charger-
import flash.display.Sprite;
import flash.events.*;
import flash.net.*;
//load image
var loader:Loader = new Loader();
var url = "C:\\Data\\cutcord.jpg";
var urlReq:URLRequest = new URLRequest(url);
configureLoader(loader.contentLoaderInfo);
loader.load(urlReq);
function completeHandler(event:Event):void {
var imageIn:BitmapData = event.target.content.bitmapData;
var byteArray:ByteArray = imageIn.getPixels(imageIn.rect);
var newBitmapData:BitmapData = imageIn.clone();
newBitmapData.setPixels(imageIn.rect, byteArray);
var newBitmap:Bitmap = new Bitmap(newBitmapData,"auto",true);
this.addChild(newBitmap);
}
function configureLoader(dispatcher:IEventDispatcher):void {
dispatcher.addEventListener(Event.COMPLETE, completeHandler);
}
Here's a way to do it.
I broke it upward into 2 parts. Part is in charge of the original image (to create the ByteArray of).
Second part (loadImageData()) uses the Base64 encoded ByteArray and convert into an image and display it.
import flash.display.Loader; import flash.net.URLRequest; import flash.display.Bitmap; import com.dynamicflash.util.Base64; import flash.display.BitmapData import flash.geom.Rectangle; var loader:Loader; var req:URLRequest; var orig_mc:MovieClip; var copy_mc:MovieClip; var imgWidth:int; var imgHeight:int; var b64Img:String; function loaderCompleteHandler(evt:Event):void { trace("Application ::: loaderCompleteHandler"); var ldr:Loader = evt.currentTarget.loader as Loader; var origImg:Bitmap = (ldr.content as Bitmap); imgWidth = origImg.width; imgHeight = origImg.height; var origBmd:BitmapData = origImg.bitmapData; var rect:Rectangle = new Rectangle(0,0,origImg.width, origImg.height); var ba:ByteArray = origBmd.getPixels(rect); trace(" - bytearray length: ", ba.length); // Base64 encode - this is what gets stored (in xml or whatever) b64Img = Base64.encodeByteArray(ba); //trace("b64Img: ", b64Img); // now (pretend) to load the data loadImageData(); } function loadImageData():void { trace("Application: loadImageData"); // use b64Img as if it was loaded from xml // decode Base64 string to ByteArray var ba:ByteArray = Base64.decodeToByteArray(b64Img); trace(" - bytearray length: ", ba.length); // create Rectangle, same size as original var rect:Rectangle = new Rectangle(0, 0, imgWidth, imgHeight); // crate BitmapData and throw bytearry at it var bmd:BitmapData = new BitmapData(imgWidth,imgHeight, false, 0x00000000); bmd.setPixels(rect, ba); // create (smooth) bitmap from data var bm:Bitmap = new Bitmap(bmd, "auto", true); // display bitmap in movieclip copy_mc.addChild(bm); copy_mc.x = imgWidth + 10; } loader = new Loader(); req = new URLRequest("2.jpg"); loader.load(req); loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderCompleteHandler); orig_mc = new MovieClip(); orig_mc.addChild(loader); addChild(orig_mc); copy_mc = new MovieClip(); addChild(copy_mc);
Note that to make this work, you need to save original image width and height (in your xml) as well as the data that is encoded in Base64.
Another way to do the same thing would be to use JPGEncoder or PNGEncoder to encode the original bitmapdata.
They're both part of the Flex SDK: http://livedocs.adobe.com/flex/3/langref/mx/graphics/codec/package-detail.html
But it is also available in the AS3CoreLib: http://code.google.com/p/as3corelib/
http://code.Google.com/p/AS3corelib/downloads/list
With PNGEncoder/JPGEncoder you take the bitmapdata and convert it to a png or jpg (such as ByteArray) and that Base64 encoding.
The difference here is that you would get * real * data image than other languages can understand as well. For example, you can view the image using PHP, or whatever. The following must be able to encode the original image (jpg) BitmapData, ByteArray.
var jpg:JPGEncoder = new JPGEncoder(80); var ba:ByteArray = jpg.encode(origBmd);
To display the image you could use a Loader instance and then call loadBytes()
var loader:Loader = new Loader(); loader.loadBytes(ba); addChild(loader);
So to rebuild the image is much easier as well (no need of the height or the width of the original image).
Hope this helps
Tags: Adobe Animate
Similar Questions
-
Hello
I have a request. I have a MSSQL database into two columns. One is a varchar and the second is the Image type. I would use these two fields filled to KSOAP2. I tried to send a picture in KSOAP byte array but it did not, probably, I sometimes confuse.
Here is the source code.public byte[] getBytesFromBitmap(Bitmap bmp) { try { int height=bmp.getHeight(); int width=bmp.getWidth(); int[] rgbdata = new int[width*height]; ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); bmp.getARGB(rgbdata,0,width,0,0,width,height); for (int i = 0; i < rgbdata.length ; i++) { if (rgbdata[i] != -1) { dos.writeInt(i); dos.flush(); //l++; } } bos.flush(); return bos.toByteArray(); } catch (Exception ex) { Dialog.alert("getBytesFromBitmap: " + ex.toString()); return null; } } Bitmap borderBitmap = Bitmap.getBitmapResource("rounded.png"); byte[] img = getBytesFromBitmap(borderBitmap); String name = "Name"; SoapObject rpc = new SoapObject(serviceNamespace, "name"); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); rpc.addProperty("_img", img); rpc.addProperty("_string", name); envelope.setOutputSoapObject(rpc); envelope.bodyOut = rpc; envelope.dotNet = true; envelope.encodingStyle = SoapSerializationEnvelope.XSD;
I also tried... I transferred the image in the array of bytes to a string, using the string, I sent KSOAP and everything went well... The problem was that if she string converted to array of bytes, and then in a Bitmap, then bb do not show Bitmap. I would like to send a byte array.
Thank you
Stepan
This function is useful to get the bytes of the image.
public static byte[] returnByte(String path) { FileConnection fconn; int available = 0; InputStream input = null; byte[] data=null; try { fconn = (FileConnection)Connector.open(path); if(fconn.exists()==true) { input = fconn.openInputStream(); available = input.available(); int fSz = (int)fconn.fileSize(); data = new byte[fSz]; input.read(data, 0, fSz); } } catch(Exception e) { Dialog.alert("Error"); } return data; }
Now you must do this:
Byte [] img = returnByte ("pawan.png");
rpc.addProperty("_img", Base64.encode(img));
I'm sure it works...
Thank you
-
I'm trying to convert an array of bytes into a bitmap image. The byte array returned from a url, if you enter the url in Internet Explorer, it is automatically returned. What would be the best way to get the data returned by the url, and how would it be better to convert as bitmap?
There is an example here:
-
How to convert an array of bytes in a single integer
Hello!
So, for the moment, I am trying to receive data from a device that sends data back as an array of 10 bytes, where the first 2 bytes are a header, 6 are a number of words that is supposed to be a unique 48-bit value and the last 2 are a number of errors which is suppose to be a unique 16-bit value.
Ex:
Word has received
(Header) (----------------------------------Word Count------------------------------) (Number of errors)
0 120 0 44 221 155 96 48 0 0So, in theory, what I want to do is be able to calculate the values like this:
(Header) (----------------------------------Word Count------------------------------) (Number of errors)
0 120 0 44 221 155 96 48 0 0
The binary values: 00000000 00101100 11011101 10011011 01100000 00110000 00000000 00000000
Concat. Vals: 000000000010110011011101100110110110000000110000 0000000000000000
Calc'd Vals: = 192696508464 words = 0 errors
* 40 (40-bit words)
Totals: = 7.7078603e + 12 bits total = 0 Total errorsBut the problem that I am running is that all methods that I use seem to not be correct.
I tried:
Flatten the data and then it unflattening like a U64
Convering to bool, concatinating tables data, and then convert that to a certain number
Join all the bytes together using the join function
Casting to an array of bytes to a U64
And with all methods, the data that I use is incorrect (in the sense where the values are incorrect compared to this calculation manually like I did above), and at this point, I'm not sure how to get the correct values, so any kind of help would be greatly appreciated!
Thank you!
It seems to work for me...
-
What is the best way to convert an array of bytes or string cluster
I am writing a program that sends UDP packets and I defined the data I want to send via large groups (with numbers of u8, u16/u32, u16/u8/u32 tables and nested groups). Just before sending the data, I need to convert groups or chains of arrays of bytes. The flatten the string function is almost perfect for this. However, it is addition of lengths in the tables and strings that makes this unusable method, because as far as I can tell.
As I have many of these groups, I would rather not hard code the unbundle names and conversion/cast of strings or arrays of bytes for each of them.
Y at - it a function, or a tool that I'm on?
Thank you!
mkirzon wrote:
The program I'm developing is to communicate and to poll an external device that includes a Protocol well documented. The messages that I built in clusters contain components accurate that expected from the other device. So, if my program adds any additional info (such as this array/string lengths), monitor the device external won't recognize messages and returns an error.
Unfortunately, you have to ungroup your cluster and collect the individual channels to concatinate.
-
Problem of cast to array of bytes in array of float
Can someone help me find this process I am doing wrong?
- I read a string of 6 tanks during the series.
- I take the string and convert it to an array of bytes.
- I then reverse the byte array because my microcontroller first sends the LSB and Labview is Big-endian
- I catalogued this table in an array of float
- I invert the table again to retrieve the data in the original order
I can see the bytes in the array of bytes as 'byte, 0, 0, 0' when there are a small number, but when I I cataloged get very large or very small floats. Can someone help me understand this?
Thank you!
LabVIEW 2011
You should probably use string unflatten, select the byte with rule of the little order and use a DBL 1 d array type. Everything must fall in place without all these gynastics bit, what you're doing.
You can show us your code? I don't understand your use of "decimate the table."
Attach a small VI containingh a typical chain received as a constant of diagram.
-
Array of bytes to double signs for AutoPowerSpectrum
I'm trying to analyze a wav file and get the thd.
During the read wav file, I read in one data (void *) table. And according to the type of bit, depends on how to call PlotWaveform. So, in my example, I have a 16-bit mono signal. And I'm calling draw the waveform as follows:
PlotWaveform (panelHandle, PANEL_CHANNEL_LEFT, channel1, samplesPerChannel, type, 1.0, 0.0, 0.0, 1.0, VAL_THIN_LINE, VAL_EMPTY_SQUARE, VAL_SOLID, 1, VAL_RED);
And a perfect sine wav out.
Now, I try to do the THD on the signal, but can't convert my array of bytes in a double table. I have the following code, but all my values that I use are in power - 319th.
channel 1 is a (void *)
I guess that the ConvertArrayType () function can help you in this problem.
-
Large array of bytes sent via socket?
Hello
I have had this problem for a while and have never really stood under how to solve it properly. I don't understand how you are supposed to transfer arrays of bytes that are larger than the size of the buffer of the socket. I have semi overcome them chapter by chapter from the table and write through the sleeve and reassemble frequently on the other side, but this causes problems. What is the right way to send a byte array that is larger than the buffer socket on an outputstream?
I suspect that I am thick here, but I'm not aware that there is something called a socket buffer. Actually, let me rephrase. I'm not aware that there is a specific size that was a little to the amount of data to a socket can accept.
And you should, in theory, be able to send constantly bytes on a socket and the IP protocol should ensure that they arrive in the right order, at the other end, providing the connection is maintained.
In practice there are limits, but I wasn't aware of a buffer size of socket specific related to the shots of Blackberry (or any Sockets besides /).
The original poster might explain what determines the size of this buffer?
-
Sending the command apdu with an array of bytes as CDATA
Hello
I learn the java card as part of my final year project. So far I think I can do the most basic things, but I stuck a special moment.
I know that there are different manufacturers to create an apdu command object and a number of these manufacturers take an array of bytes as CDATA values.
My problem is, how do I access this data table in the side of the card because apdu.getBuffer () returns an array of integers (bytes)? And what is actually on apdu.getBuffer () [ISO7816. (Instead of OFFSET_CDATA)] when you send the apdu command object using such constuctor?
concerning
Published by: 992194 on 6 March 2013 06:12992194 wrote:
(..) I should have mentioned earlier that my card use jc 2.2.1 version, and from different places, I've read that this version does not support ExtendedLength facilities.Indeed.
I also understand the semantics of apdu.getBuffer () [ISO7816. OFFSET_CDATA] is the first byte of the data command. My question is, these command data was initially provided as an array of bytes. Something like this:
+ new CommandAPDU(CLA, INS, P1, P2, DATA_ARRAY, Le) +.
For example, when you call:
ubyte [] buffer = apdu.getBuffer)
So it means that the values of bytes inside the tableau_donnees argument automatically occupy locations + buffer [ISO7816. OFFSET_CDATA] + inside the buffer?
Yes. The length would be (abstract) (buffer [ISO7816. (OFFSET_LC] & 0xFF) . Notice the & 0xFF is a must greater than 127 bytes.
Or there is a mechanism to extract the table tableau_donnees itself?
Laughing out loud
In fact, in the interest of performance and portability in environments with low memory, usual coding style must pass buffer , an offset that and length; rather than take an object, which would require a copy. Welcome to the real world of Java Card.
-
Array of bytes in JSON string is not a valid JSONObject.
I get an array of bytes from a URL that I can view in Google Chrome as a valid JSON object.
When I get the answer to IOUtilities.streamToBytes (), it returns in the following way:
[16, 8, 1, 10, 2,... 1, 0, 0, 8, 0, 0, 120, 2, 0]
How can I convert the byte array to a human readable string I can spend in the JSONObject constructor?
I tried the following character encodings:
- "ISO-8859-1".
- 'UTF-8 '.
- "UTF-16BE".
- "US-ASCII".
Hello
First, check with your http connection that it returns the appropriate response.
connection=(HttpConnection)Connector.open(url,Connector.READ); connection.setRequestMethod(HttpConnection.GET); if(connection.getResponseCode()==HttpConnection.HTTP_OK) { inputstream=connection.openInputStream(); int ch; buffer=new StringBuffer(); while((ch=inputstream.read())!=-1) { buffer.append((char)ch); } System.out.println(buffer.toString()); }
If so, you need to spend just that data in json for parsing.i
Thankx
-
array of byte size limit]
I download & save multimedia files (video/pdf) using following code. The question is his works well for small size files MB (1 MB to 18 mb), but for some 60 MB files it stuck during the download. or sometimes download does not start. Thr is a size limit for byte array coz I am booting with the length of the file. This len contains the bytes to be read
int
Len = (int) hc.getLength ();
byte data = newbyte[len];
if (len > 0) {
intactual = 0;
intBytesRead = 0;
while ((bytesread! = len) & (real! = - 1)) {
real =
tell. Read (data, bytesread, len - bytesread);
bytesRead += real;
percentage = bytesread * 100;
percentage = percentage / len;
int p = percentage (int);
ProgressIndicatorScreen.
this.model.setValue (p);
}
}
I don't think that there is a size limit for an array of bytes, this is probably a problem with the connection. Download large files has been difficult for ever.
-
Hello
When I try to start my database, I get this error:
SQL > startup;
ORACLE instance started.
Total System Global Area 8551575552 bytes
Bytes of size 2245480 fixed
2365590680 variable size bytes
6157238272 of database buffers bytes
Redo buffers 26501120 bytes
Mounted database.
ORA-03113: end of file on communication channel
Process ID: 9789
Session ID: 321 serial number: 3
I checked the alert log file and concluded that,
Errors in the /u01/app/oracle/diag/rdbms/dev/dev/trace/dev_arc1_11834.trc file:
ORA-19815: WARNING: 42949672960 bytes db_recovery_file_dest_size is 100.00% used and has 0 bytes remaining available.
************************************************************************
You have choice to free up space in the recovery area:
1 consider changing STRATEGY OF RETENTION of RMAN. If you are using Data Guard
then consider changing POLICY of DELETE ARCHIVELOG RMAN.
2 back up files on a tertiary device such as a tape with RMAN
SAFEGUARDING RECOVERY AREA command.
3. Add space drive and increase the db_recovery_file_dest_size setting to
reflect the new space.
4 remove the unnecessary files using the RMAN DELETE command. If a service
the system control has been used to remove the files, and then use the RMAN DUPLICATION and
Commands DELETE has EXPIRED.
************************************************************************
Arc1: 19809 error creating archive log file at "+ RECO.
ARCH: Stopped archiving, error occurred. Will continue to retry
ORACLE Instance dev - archive error
ORA-16038: log sequence 1 # 46 can be archived
ORA-19809: limit exceeded for file recovery
ORA-00312: 1 1 online journal thread: "+ REDO/dev/onlinelog/group_1.284.879765261".
To do this,
I can't connect to database, so I deleted the archivelogs manually from + RECO/DEV/ARCHIVELOG/and tried to start the database once again, still the same error.
The problem here is that I can't open the database, so I am unable to increase db_recovery_file_dest_size or connecting to RMAN and remove the archivelogs.
Any suggestions on how to fix this?
Thank you
bootable media;
Than the command again a problem.
ALTER system set db_recovery_file_dest_size = 50G scope = both;
ALTER database open;
Best regards
mseberg
-
Pass an array of bytes to the oracle stored procedure
I have a problem with moving from byte array in Oracle stored procedure as an input parameter by using odp.net.
Here is the signature of the stored procedure:
SOMEPROCEDURE(session IN NUMBER, data IN RAW)
Here is c# code, which calls the procedure:
var cmd = new OracleCommand("SOME_PROCEDURE", _connection);
cmd.CommandType = CommandType.StoredProcedure;
var bt = new byte[]{1,68,0,83,128,1};
OracleParameter sessionId = new OracleParameter("dbSessionId", OracleDbType.Decimal, new OracleDecimal(_dbSessionId), ParameterDirection.Input);
OracleParameter data = new OracleParameter("statusData", OracleDbType.Raw, new OracleBinary(bt), ParameterDirection.Input);
cmd.Parameters.Add(sessionId);
cmd.Parameters.Add(data);
cmd.ExecuteNonQuery();
This code does not (stored procedure throws exception, which cannot receive), because in byte array hadou number 128!, if I display 128 on another number, minus 128, it works great!
What should I do?
After some tests I found the solution. Initially, you cannot switch to the array of bytes via the odp.net stored procedure, if the table contains 127 large values.
Yes, solution: 1. create the wrapper procedure
procedure SOME_PROCEDURE_WRAPPER (p_session_id in number, p_data in varchar2)
is v_data raw(1024);
rawdata raw(1024);
rawlen number;
hex varchar2(32760);
i number;
begin
rawlen := length(p_data);
i := 1;
while i <= rawlen-1
loop
hex := substrb(p_data,i,2);
rawdata := rawdata || HEXTORAW(hex);
i := i + 2; end loop;
SOME_PROCEDURE(p_session_id , rawdata);
end;
2 then need to modify the code c# in this way:
var cmd = new OracleCommand("SOME_PROCEDURE_WRAPPER", _connection);
cmd.CommandType = CommandType.StoredProcedure;
string @string = statusData.ToHexString();
OracleParameter sessionId = new OracleParameter("dbSessionId", OracleDbType.Decimal, new OracleDecimal(_dbSessionId), ParameterDirection.Input);
OracleParameter data = new OracleParameter("statusData", OracleDbType.Varchar2,@string.Length, new OracleString(@string), ParameterDirection.Input);
cmd.Parameters.Add(sessionId);
cmd.Parameters.Add(data);
cmd.ExecuteNonQuery();
where
public static string ToHexString(this byte[] bytes)
{
if(bytes == null || bytes.Length == null)
return string.Empty;
StringBuilder hexStringBuilder = new StringBuilder();
foreach (byte @byte in bytes)
{
hexStringBuilder.Append(@byte.ToString("X2"));
}
return hexStringBuilder.ToString();
}
-
Can I make a Flash frame as a bitmap and send over TCP/IP?
I want to draw some combinations of bitmaps, vectors, flash, text etc and forms draw programmatically in my film using ActionScript and then get each pixel "rendered" my film (to the 100% view) in a table that I send to another program over TCP/IP. Can someone help me out here?
The first part of the question is if its possible to render a frame which is a collection of Flash elements as bitmap? I know that I can browse a bitmap and get every pixel using getPixel method but I'm trying to access the last image rendered on my screen, including, as I said text and Flash Forms.
The second question is what would be the best way to send this "video image" on TCP/IP? Can I use a XML socket connection? It's the only way I know how to send data from Flash over TCP/IP, but I don't know that if this is the only way - the help page indicates the data must be in XML format, which seems heavy for this application.
I am now using Max/MSP/Jitter to make a screenshot, the size and the location of my Flash movie and then send the resulting matrix with a 'jit.net.send' object (which lets send you video over TCP/IP frames), but it's too awkward for installation that I'm building.
Any help would be greatly appreciated!
-bob
If you want to see is a single item, you can create a bitmapdata object and then call the draw() method and pass the movieclip containing all your assets.
As for the second part, I'm not sure about this.
-
compression of image and convert between Bitmap and byte]
Hello
I'm trying to compress an image raw data(byte[]), and here's what I did:
Bitmap image = Bitmap.createBitmapFromBytes( _raw, 0, -1, 7 ); Bitmap scaledBitmap = new Bitmap(192, 144); image.scaleInto(scaledBitmap, Bitmap.FILTER_BILINEAR, Bitmap.SCALE_TO_FIT);
So now that I have a compressed Bitmap, scaledBitmap and I want the gross data(byte[]) extract from the scaledBitmap. I noticed there is a getRGB565 method, but I don't know how to use it. Can someone give me an example on how to extract the raw data? If it is not possible, is there another way to compress the _raw?
Thanks in advanc
I found the solution:
Bitmap image = Bitmap.createBitmapFromBytes( _raw, 0, -1, 8 ); int newWidth = 192; int newHeight = 144; Bitmap scaledBitmap = new Bitmap(newWidth, newHeight); image.scaleInto(scaledBitmap, Bitmap.FILTER_BILINEAR, Bitmap.SCALE_TO_FIT); PNGEncodedImage encoder = PNGEncodedImage.encode(scaledBitmap); byte[] resizedBytes = encoder.getData();
Maybe you are looking for
-
HP Color LaserJet CP5520 "impossible Operation completed (error 0 x 00000057).
I'm trying to install the drivers on a print server on Windows Server 2008 x 64 for a printer HP Color LaserJet series 5520. Someone tried to run the installation package for the 64-bit driver and brought the print server. He installed the HP print m
-
Have several recording which are VOB files. Can play with WMP, but at the end they loop any if I clicked on the "round repeat or not." Is it possible to have the video stop after he plays? Thank you L.
-
Formatting hard drive using Vista Home Premium
I am a 1.5 TB hard drive formatting and it seems to be suspended at around 73% is - this normal and how many hours must this process normally take. I had to cancel the formatting process, once for lack of time, but he had run for about 12 hours. Ther
-
reconfigure the printer problem
I deleted by mistake my J6480 OfficeJet from my control panel, so I tried to reinstall the software. The printer will work as long as it is connected to my usb cable, but I can't get the wireless option to work. I tried to reconfigure, but he doesn
-
Running Win7 x 64 home. I have multiple problems of game about Dx11. EverQuest Games Inc., World of Warcraft, Doom3, Farcry, Alien Vs Predator 2 (former), Counterstrike and a crowd of older games! I read the other messages and responses (those who re