Converting image to byte array? [closed] - image-processing

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
What is the need/purpose of converting an image to a byte array?
Why do we need to do this?

What's the purpose of converting an Image to a byte array?
Saving an image to disk
Serializing the image to send to a web service
Saving the image to a database
Serializing the image for processing
...are just a few that I can think of off the top of my head.

I think the most common use would be saving an image in a database (BINARY(MAX) data type).

Most common is to persist the image in the database as a blob (binary large object) but it could also be used in web services where you could take in a byte array as a method argument and then convert that to an image for whatever reason.

the only time i've ever needed to do this was to compare two images pixel-by-pixel to see if they were identical (as part of an automated test suite). converting to bytes and pinning the memory allowed me to use an unsafe block in C# to do a direct pointer-based comparison, which was orders of magnitude faster than GetPixel.

Recently I wrote a code to get hash from image, here is how:
private ImageConverter c = new ImageConverter();
private byte[] getBitmapHash(Bitmap hc) {
return md5.ComputeHash(c.ConvertTo(hc, typeof(byte[])) as byte[]);
}
Here is this in context. Serializing image or adding it to database in raw byte format (without mime type) is not something that seems to be sensible, but you can do that. Image processing and cryptography are most likely of places where this is useful.

To further generalize what Brad said: Serialization and (probably) a basis for object comparison.

Also is helpful if you have a image in memory and want to send it to someone via a protocol (HTTP for example). A perfect example would be the method "AddBytesForUpload" in the Chilkat HTTPRequest clas [http://www.chilkatsoft.com/refdoc/vbnetHttpRequestRef.html].
Why would you ever need to do this you may ask... Well lets assume we have a directory of images we want to auto upload to imageshack, but do some mods before hand like put our domain name at the bottom right. With this, u load the image in memory, do the mods with it that u need, then simply attach that stream to the HTTPRequest object. Without the array u would need to then same to a file before uploading, which in turn will create either a new file u then need to delete after, or over write the original, which is not always ideal.

public byte[] imageToByteArray(System.Drawing.Image image)
{
MemoryStream ms = new MemoryStream();
image.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}

If it is a image file use File.ReadAllBytes().

Related

Using Dart for HTML5 app, but want to load a file from the server-side

I'm new to Dart, and trying to create my first Dart web game. Sorry if I missed an answered question related to this. I did search, but wasn't having much luck.
To load a level, I would like to be able to read in a text file with the level data, then process that and use it to build the level. Unfortunately, I am running into the issue where dart:io and dart:html can not both be loaded if you want to use the File() object. From what I can tell, dart:html's File() object is client-side, so that would not be able to open the text-file I will have on the server.
Is there another way to read in a text file from the server? If not, do I need to set up a database just to store the game data, or is there a better option I'm not thinking about here?
In case it helps, the game data I'm working with currently is just a text file that gives a map of what the level will look like. For example:
~~~~Z~~~~
P
GGGGLLGGG
Each of those characters would denote a type of block to be placed in the level. It's not the best way to store levels, but it is pretty easy to create and easy to read in and process.
Thanks so much for the help!
If the file you are loading is a sibling of the index.html your game is loaded from, then you can just make an HTTP request to fetch the file.
To download web/level1.json you can use
Future<String> getGameData(String name) {
var response = await HttpRequest.getString('${name}.json');
print(response);
return response;
}
otherMethod() async {
var data = await getGameData('level1');
}
See also https://api.dartlang.org/stable/1.24.3/dart-html/HttpRequest-class.html

How do I best convert raw pixel data to a PNG file?

(I'm working on a Xamarin.Forms project targeting iOS, but I get the feeling I need to use monotouch to accomplish my goals.)
I have an array I get from a function, and this array represents some bitmap data I would like to save and display later. I've been looking at the documentation, and I don't see a path from bytes to bitmap to file that is as clear as I'd expect. In WinForms, I'd create a System.Drawing.Bitmap, then use the Save() method. In Xamarin for Android, Android.Graphics.Bitmap has a Compress() method that lets me output to a stream. I'm having trouble figuring out what the equivalent in Xamarin iOS would be.
The pixel data is 32 bits per pixel, 8 bits per component, ARGB. I've got as far as figuring out I can create a CGImage from that, currently via a CGBitmapContext. I can get a UIImage from that, but the next clear method is UIImage.SaveToPhotoStream() which isn't what I want to do. I see AsPng() returns an NSData, and that seems like a way to go. I don't quite have it working yet (because for some reason the provider decided to output int[] instead of byte[]) but I'm curious: is there an easier way to go from raw pixel data to a PNG file?
You can use ImageIO that gives you a little bit more control over what to serialize.
You still need to get yourself a CGImage to work with though.
Use one of the three CGImageDestination.Create overloads to select the kind of output you want to produce (save to a NSMutableData object, to an NSUrl, or to your own data provider), add the image, and then close the CGImageDestination.
Something like this:
var storage = new NSMutableData ()
var dest = CGImageDestination.Create (storage, MobileCoreServices.UTType.PNG, imageCount: 1);
dest.AddImage (yourImage);
dest.Close (); // This saves the data
You can change the parameter in Create for imageCount to other numbers if you want to create images that have multiple frames, in that case, you will also call AddImage repeatedly.
If you are looking to write the image to a file then it would be quite simple:
var bytes = image.AsPNG().ToArray();
await stream.WriteAsync(bytes, 0, bytes.Length);

Phone Number detection and calling [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
i am developing the BlackBerry app in which the data comes from the web services.The data contains the phone numbers of the different countries and also there is call functionality in the app.
I have used ActiveRichTextField to display data in labelfield so that phone numbers and email id's can be detected.It also detects the numbers and mail id's but it fails to detect some of the numbers.Do any body know how to detect number such as +618 12345678/79 and sort of the data.Any sort of help is appreciated.
If you are looking to recognise a string in another given string, you want to look at PatternRepository. This is a system managed collection of strings, that is used to add context menus to given strings.
If your string is found on the device, it will show the menu that you define. So you need to subclass ApplicationMenuItem and provide your own run() method.
The following code will set up your device to recognise a regular expression, and create a context menu item for when that pattern is found:
// MyAppMenuItem extends ApplicationMenuItem
MyAppMenuItem appMenuItem = new MyAppMenuItem(0);
ApplicationMenuItem[] applicationMenu = new ApplicationMenuItem[1];
applicationMenu[0] = appMenuItem;
// register the pattern to identify the phone number
PatternRepository.addPattern(
ApplicationDescriptor.currentApplicationDescriptor(),
"*** REGEXP String to recognise phone numbers ***",
PatternRepository.PATTERN_TYPE_REGULAR_EXPRESSION,
applicationMenu);
I found that this does not work in HTML fields (BlackBerry - intercept text in HTML). But it worked in almost all other places across my app, and in other apps, like email. If you only want it to work in your app, you can deregister this pattern when your app exits.
Note that you can add many different patterns to the PatternRepository - one for each style of number or email address that you want to recognise.

Best Way To Store Tons of Data

I'm working on an application that will need to pull from a list of data depending on where the user is located in the US. In a sense, I will have a database full of information based on their location, and a condition statement will determine while value from the list to use.
Example of data:
Tennessee:
Data2 = 25;
Data3 = 58;
...
Texas:
Data2 = 849;
Data3 = 9292;
...
So on...
My question is, what is the best practice to use when developing iOS apps and you have a lot of data? Should you just put all the related data in a file, and import that file when you need to like normal, or is there another method you should use? I know they state you should follow the MVC practice, and I think in this case my data would be considered the Model, but just want to double check if that applies here.
You have some options here:
SQLite database
Core Data (its not a relational database model like sqlite)
write to plain text file. (using NSFileManager )
NSKeyedArchiever
If you want to frequently keep appending data to a single file, I would recommend using sqlite fast and robust.

Erlang and the records

What is wrong in this code?
I was expected "titi" in person.name but I still have "toto"!
More explicitly, how to modify a record in a function?
init1()->
S=#person{name="toto"}, %record creation and field setting
fct(S),
io:format("~s~n",[S#person.name]).
fct(R)->
R#person{name="titi"}. %record updating
You need to get a result of fct():
init1()->
S=#person{name="toto"}, %record creation and field setting
S2 = fct(S), % Get updated record
io:format("~s~n",[S2#person.name]).
fct(R)->
R#person{name="titi"}. %record updating
Bertaud, I think you are getting ahead of yourself a bit. You really need to understand the basics of immutability before you write any more code. (i.e. "variables" do not vary : you can only assign a value to them once.) I suggest you read the free online guide "Learn You Some Erlang For Great Good", at http://learnyousomeerlang.com/. The section that covers the basics of variables is http://learnyousomeerlang.com/starting-out-for-real#invariable-variables.
It is impossible to stress too much that all data in Erlang is immutable. So to do something like in your original question you need to modify it like #hdima did. The record is not updated but rewritten. In the same way there is no global data in Erlang, all data belongs to a process. This is even true of ETS tables as they basically behave like a process, albeit a built-in one without explicit communication.
So if you use the process dictionary or an ETS table the data itself can never be updated, only the dictionary/table. This means that to modify some data in the dictionary/table you basically have to:
"Read" the data
Update the data making new data
"Write" the new back into the dictionary/table
Without writing the new data back into the dictionary/table it will be lost, as your new data was.
Within fct(), you're not mutating the record, but you're returning a new value for the record, which needs to be used further. If you're calling fct(S), without handling the return value, then you'll lose that new value ("titi").

Resources