Byte array as a blob
Please show me someone an short example to store an byte[] as a blob and
restore it.
(.java and .jdo files).
Thank you,
Mihai
My configuration is:
- DB : MySql 3.23.38
- Kodo : 2.2.6 (also 2.3.0 beta)
- i use JBuilder Kodo open-tool , another problem is 2.3.0 JBuilder Kodo
open-tool which is not working for a project previous configured with 2.2.6
(=> kodo.properties).
- another thing do say is "double" values stored in db. For example if i put
2.0 double value in db , then when i read this value from db, a 1.99999
double value is returned (but i read that bug also in your manual).
(thank you for your tip)
Abe White <[email protected]> wrote in message
news:agmtu0$o3e$[email protected]..
What database are you using? Let me know and I'll log this as a bug. Thereason it's happening is that we use ObjectOutput.writeObject() to write
blobs to the database, even if they're already a byte array. And as we read
them back in, it appears that in some databases we don't properly use
readObject() to get rid of the extra bytes serialization inserts. To get
around the bug temporarily, you could do this yourself (i.e. bytes =
(byte[]) new ObjectInputStream (new ByteArrayInputStream (bytes)).readObject
>
Similar Messages
-
How to split the blob byte array and insert in oracle
how to split the blob byte array and insert in oracle
I am having a string which is of more than lenght 4000 so i am using BLOB datatype as input to get the string.
need to split the blob in oracle and store in the different column
The string is of bytearray i need to strore it in each column based on the byte array.this will be my input i need to split the above and store it in different columns in a table.
for spliting say
Column1 -1 byte
Column2-3 byte
Column3-5 byte
ColumnN-5 byte
Table will have corresponding data type
Column1 - number(10,2)
Column2 - Float
Column3 - Float
ColumnN-Float
here Column2 datatype is float but it will always have 3 byte information.
where as Column3 datatype is also float but it will always have 5 byte information.
Say N is Column 120 -
Convert byte array to table of int
[http://www.codeproject.com/KB/database/PassingArraysIntoSPs.aspx?display=Print|http://www.codeproject.com/KB/database/PassingArraysIntoSPs.aspx?display=Print] Hello friends.
I'm pretty new with PL/SQL.
I have code that run well on MSSQL and I want to convert it to PL/SQL with no luck.
The code converts byte array to table of int.
The byte array is actually array of int that was converted to bytes in C# for sending it as parameter.
The TSQL code is:
CREATE FUNCTION dbo.GetTableVarchar(@Data image)
RETURNS @DataTable TABLE (RowID int primary key IDENTITY ,
Value Varchar(8000))
AS
BEGIN
--First Test the data is of type Varchar.
IF(dbo.ValidateExpectedType(103, @Data)<>1) RETURN
--Loop thru the list inserting each
-- item into the variable table.
DECLARE @Ptr int, @Length int,
@VarcharLength smallint, @Value Varchar(8000)
SELECT @Length = DataLength(@Data), @Ptr = 2
WHILE(@Ptr<@Length)
BEGIN
--The first 2 bytes of each item is the length of the
--varchar, a negative number designates a null value.
SET @VarcharLength = SUBSTRING(@Data, @ptr, 2)
SET @Ptr = @Ptr + 2
IF(@VarcharLength<0)
SET @Value = NULL
ELSE
BEGIN
SET @Value = SUBSTRING(@Data, @ptr, @VarcharLength)
SET @Ptr = @Ptr + @VarcharLength
END
INSERT INTO @DataTable (Value) VALUES(@Value)
END
RETURN
END
It's taken from http://www.codeproject.com/KB/database/PassingArraysIntoSPs.aspx?display=Print.
The C# code is:
public byte[] Convert2Bytes(int[] list)
if (list == null || list.Length == 0)
return new byte[0];
byte[] data = new byte[list.Length * 4];
int k = 0;
for (int i = 0; i < list.Length; i++)
byte[] intBytes = BitConverter.GetBytes(list);
for (int j = intBytes.Length - 1; j >= 0; j--)
data[k++] = intBytes[j];
return data;
I tryied to convert the TSQL code to PL/SQL and thats what I've got:
FUNCTION GetTableInt(p_Data blob)
RETURN t_array --t_array is table of int
AS
l_Ptr number;
l_Length number;
l_ID number;
l_data t_array;
BEGIN
l_Length := dbms_lob.getlength(p_Data);
l_Ptr := 1;
WHILE(l_Ptr<=l_Length)
loop
l_ID := to_number( DBMS_LOB.SUBSTR (p_Data, 4, l_ptr));
IF(l_ID<-2147483646)THEN
IF(l_ID=-2147483648)THEN
l_ID := NULL;
ELSE
l_Ptr := l_Ptr + 4;
l_ID := to_number( DBMS_LOB.SUBSTR(p_Data, 4,l_ptr));
END IF;
END IF;
l_data(l_data.count) := l_ID;
l_Ptr := l_Ptr + 4;
END loop;
RETURN l_data;
END GetTableInt;
This isn't work.
This is the error:
Error report:
ORA-06502: PL/SQL: numeric or value error: character to number conversion error
06502. 00000 - "PL/SQL: numeric or value error%s"
I think the problem is in this line:
l_ID := to_number( DBMS_LOB.SUBSTR (p_Data, 4, l_ptr));
but I don't know how to fix that.
Thanks,
MTs.I'd found the solution.
I need to write:
l_ID := utl_raw.cast_to_binary_integer( DBMS_LOB.SUBSTR(p_Data, 4,l_ptr));
instead of:
l_ID := to_number( DBMS_LOB.SUBSTR (p_Data, 4, l_ptr));
The performance isn't good, it's take 2.8 sec to convert 5000 int, but it's works. -
Error when creating BufferedImage with IndexColorModel from a byte array.
Hi, I have a 1-dimentional byte array and an IndexColorTable, and I can't figure out how to combine the 2 into an BufferedImage without unnecessary copying/reallocating of the image buffer.
The color model I have is:
int [] cmap = new int [numColors];
cmap[i++] = 0xffa0f000; /etc.
new IndexColorModel(8, 22, cmap, 0, true, transparentIndex, DataBuffer.TYPE_BYTE );Thanks for your help
-Ben
Ps.
I've was looking at some example code (http://javaalmanac.com/egs/java.awt.image/Mandelbrot2.html?l=rel), and can't figure out how to go from the color model they're using to the one I have (the 8 bit one specified above). When I replace the 4bit colormodel in the code below with the 8bit color model specified above, I get the following error:
[java] java.lang.IllegalArgumentException: Raster ByteInterleavedRaster: width = 5120 height = 3520 #numDataElements 1 dataOff[0] = 0 is incompatible with ColorModel IndexColorModel: #pixelBits = 8 numComponents = 4 color space = java.awt.color.ICC_ColorSpace@c51355 transparency = 2 transIndex = 22 has alpha = true isAlphaPre = false
[java] at java.awt.image.BufferedImage.<init>(BufferedImage.java:613)
Code:
byte[] pixelArray = (byte[]) getData_CHAR();
int width = 5120;
int height = 3520;
int numbytes = width*height;
//create DataBuffer using byte buffer of pixel data.
DataBuffer dataBuffer = new DataBufferByte(pixelArray, numbytes, 0);
//prepare a sample model that specifies a storage 8-bits of pixel data in an 8-bit data element
int bitMasks[] = new int[]{0xf};
SinglePixelPackedSampleModel sampleModel = new SinglePixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, bitMasks);
//create a raster using the sample model and data buffer
WritableRaster writableRaster = Raster.createWritableRaster(sampleModel, dataBuffer, new Point(0,0));
//generate 16-color model
byte[] r = new byte[16];
byte[] g = new byte[16];
byte[] b = new byte[16];
r[0] = 0; g[0] = 0; b[0] = 0;
r[1] = 0; g[1] = 0; b[1] = (byte)192;
r[2] = 0; g[2] = 0; b[2] = (byte)255;
r[3] = 0; g[3] = (byte)192; b[3] = 0;
r[4] = 0; g[4] = (byte)255; b[4] = 0;
r[5] = 0; g[5] = (byte)192; b[5] = (byte)192;
r[6] = 0; g[6] = (byte)255; b[6] = (byte)255;
r[7] = (byte)192; g[7] = 0; b[7] = 0;
r[8] = (byte)255; g[8] = 0; b[8] = 0;
r[9] = (byte)192; g[9] = 0; b[9] = (byte)192;
r[10] = (byte)255; g[10] = 0; b[10] = (byte)255;
r[11] = (byte)192; g[11] = (byte)192; b[11] = 0;
r[12] = (byte)255; g[12] = (byte)255; b[12] = 0;
r[13] = (byte)80; g[13] = (byte)80; b[13] = (byte)80;
r[14] = (byte)192; g[14] = (byte)192; b[14] = (byte)192;
r[15] = (byte)255; g[15] = (byte)255; b[15] = (byte)255;
//create buffered image
ColorModel colorModel = new IndexColorModel(4, 16, r, g, b);
BufferedImage image = new BufferedImage(colorModel, writableRaster, false, null);Message was edited by:
ben_weisburd
Message was edited by:
ben_weisburdI had the same problem too.
anyone found the solution for this problem?
thanks
Bruno Rabino
When I try to make a MD-form, where the base-table for the detail contains a column with a BLOB-datatype. I get following error when I finish creation of the form.
Error: Exception from wwv_generate_component.build_procedure (WWV-01821)
Error creating module: ORA-01403: no data found (WWV-16042)
When I use the table with the BLOB as master or in a form, it works fine.
Has anyone else experienced this problem? Or knows a way to fix or work around it. Thanks in advance.
Portal version: 3.0.6.6.5
null -
Hello Everybody,
I need to display an image given in a byte array, how can I show this image in a JFrame?
1. I tryied saving the image in a .jpg file,
File file1 = new File("Path to my destination image");2. then I use a FileOutputStream to save the image in the path:
FileOutputStream fos1 = new FileOutputStream(docu);
fos1.write(ImageInbyteArray);
fos1.close();3. Once I have the image in a file I'm trying to load it using a JButton, but the JButton doesn't display the image. I think that for some unknown (at least for me ;-) reason the file isn't still available to be used in the ImageIcon, this is my code:
imgIconDocu = new ImageIcon("Path to my destination image");
jBtnDocu = new JButton(imgIconDocu);What's wrong here?
Thanks a lotDoes the byte array contain a JPEG image? Where did
you get the contents of the byte array?yes the array contains the JPEG image, I have a database in PostgreSQL, and the images are stored in blob in the database. I have to call a service in the server and in return it gives me the 3 images as byte arrays, that's the reason I only have the byte arrays. so I tryed saving the images as jpeg files in my hard disk to show them, but it appears that they are not available to show them in Swing after saving them. I can only show the images if I close my application and start it again :-(
I tryed flushing and closing the FileOutputStream after the writting process (fos.write(bytearrayImage);
fos.flush();
fos.close();)
Y also tryed:
fos.write(bytearrayImage);
fos.close();
fos.flush();But it doesn't work either :-(
What do you recommend me?.
Thanks a lot,
Johnny G L -
JDO : how to map a byte array field correctly
Could someone please provide an example on how to correctly map a byte array field in a PCClass.
The field should be mapped to a BLOB field in my Dictionary project.
The checker keeps throwing errors during the enhancement process. Tried all sorts of combinations of xml in my jdo and map file (using the dtd) but I still haven't found the solution. The compilation works fine though, it is only the checker that complains.You're already in a PDF open in Acrobat (not the free Adobe Reader) and you've made a new PDF? Which you want to save to disk and reopen?
-
How can i store bytes array in MS ACCESS???
Hi,
i m making small project using Ms Access as a dataBase.
In which i am encripting some confidential data say ACCOUNT_NAME and storing it into MS Access in encripted form........
The problem is encripted data is in bytes array n how can i store it into MS access ??? is there any data type similar to BLOB in Ms Access ??
please help me................
i had searched net for this but till now not found any useful info :(You can try:
binay type (JET3 255 bytes,JET4 510) Types.BINARY
ole type (0~1 G) Types.LONVARBINARY
You can use Text (JET3 255 bytes�CJET4 510bytes) Types.VARCHAR if you use base64 encoding for
ACCOUNT_NAME column. -
How to save Java byte Array in Oracle
Hi All,
I'm using Java and need to save byte Array in Database. Initially the column is varchar2 type. is it possible to save in this type or need to modify the column type to CLOB.
please clarify me.
thanks in advance.
regards
pavan.You might want to use a BLOB instead
because CLOB & varchar2 are strings unless you encode your byte array
CLOB & varchar2 datatypes won`t record 0x00 if you have any in your array
it will be considered as the string terminator -
How Do I Load An Animated GIF Into PictureBox Control From Byte Array?
I'm having a problem with loading an animated GIF int a picturebox control in a C# program after it has been converted to a base64 string, then converted to a byte array, then written to binary, then converted to a base64 string again, then converted to
a byte array, then loaded into a memory stream and finally into a picturebox control.
Here's the step-by-step code I've written:
1. First I open an animated GIF from a file and load it directly into a picturebox control. It animates just fine.
2. Next I convert the image in the picturebox control (pbTitlePageImage) to a base64 string as shown in the code below:
if (pbTitlePageImage.Image != null)
string Image2BConverted;
using (Bitmap bm = new Bitmap(pbTitlePageImage.Image))
using (MemoryStream ms = new MemoryStream())
bm.Save(ms, ImageFormat.Jpeg);
Image2BConverted = Convert.ToBase64String(ms.ToArray());
GameInfo.TitlePageImage = Image2BConverted;
ms.Close();
GameInfo.TitlePageImagePresent = true;
ProjectNeedsSaving = true;
3. Then I write the base64 string to a binary file using FileStream and BinaryWriter.
4. Next I get the image from the binary file using FileStream and BinaryReader and assign it to a string variable. It is now a base64 string again.
5. Next I load the base64 string into a byte array, then I load it into StreamReader and finally into the picturebox control (pbGameImages) as shown in the code below:
byte[] TitlePageImageBuffer = Convert.FromBase64String(GameInfo.TitlePageImage);
MemoryStream memTitlePageImageStream = new MemoryStream(TitlePageImageBuffer, 0, TitlePageImageBuffer.Length);
memTitlePageImageStream.Write(TitlePageImageBuffer, 0, TitlePageImageBuffer.Length);
memTitlePageImageStream.Position = 0;
pbGameImages.Image = Image.FromStream(memTitlePageImageStream, true);
memTitlePageImageStream.Close();
memTitlePageImageStream = null;
TitlePageImageBuffer = null;
This step-by-step will work with all image file types except animated GIFs (standard GIFs work fine). It looks like it's just taking one frame from the animation and loading it into the picturebox. I need to be able to load the entire animation. Does any of
the code above cause the animation to be lost? Any ideas?There is an ImageAnimator so you may not need to use byte array instead.
ImageAnimator.Animate Method
http://msdn.microsoft.com/en-us/library/system.drawing.imageanimator.animate(v=vs.110).aspx
chanmm
chanmm -
Convert XML data to byte array...
Hello All,
In my application, i have an XML file and the corresponding XSD file. This XML file is having some date, which i want to convert into an byte[] and then save it in a file.
How i can convert the XML data in the byte[]? Here as an example of the xml file and the byte[] data which i want to save in a file.
<?xml version="1.0" encoding="utf-8"?>
<HeadersInfo>
<header>
<id>0</id>
<Name>H1</Name>
</header>
<header>
<id>1</id>
<Name>H2</Name>
</header>
</HeasersInfo>
In the above example 'id' field is of type 'uint' and 'name' field is of type 'string' with max length of '5'. So in this case my byte array should be as shown below:
00 00 00 01 48 31 00 00 00
00 00 00 02 48 32 00 00 00
Here underlines values are for the 'id' parameter where as values in bold are for 'Name' parameter for all the header values in sequence. Name parameter is null (0x00) padded.
Thanks in advance,
IamHuMHi,
the following example extract the id, name values using LINQ To Xml and writes it to a memory stream using a binary writer and returns the result as a byte array:
internal static byte[] GetXmlAsByteArray()
var document = XDocument.Parse("<HeadersInfo>"
+ " <header><id>1</id><Name>H1</Name></header>"
+ " <header><id>2</id><Name>H2</Name></header>"
// additional testing
+ " <header><id>32767</id><Name>H1234</Name></header>"
+ " <header><id>305419896</id><Name>H56789</Name></header>"
+ "</HeadersInfo>");
const int NameLength = 5; // Max length for a name
byte[] zeroBytes = new byte[NameLength]; // Helper to fill name
using (var ms = new MemoryStream())
using (var writer = new BinaryWriter(ms))
// write each header
foreach (var header in document.Root.Elements("header"))
int id = (int)header.Element("id");
string name = (string)header.Element("Name");
byte[] nameBytes = System.Text.Encoding.UTF8.GetBytes(name);
Console.WriteLine("id: {0}, Name: {1}", id, name);
// Write id
writer.Write(GetUIntBytes((uint)id));
// Write name NameLength (5) max, otherwise padded
if (nameBytes.Length > NameLength)
writer.Write(nameBytes, 0, NameLength);
else
writer.Write(nameBytes, 0, nameBytes.Length);
if (nameBytes.Length < NameLength)
writer.Write(zeroBytes, 0, NameLength - nameBytes.Length);
byte[] result = ms.ToArray();
// dump array
foreach (var value in result)
Console.Write("{0:X2} ", value);
Console.WriteLine();
return result;
public static byte[] GetUIntBytes(uint value)
if (BitConverter.IsLittleEndian)
// swap bytes
value = ((value & 0x00ff) << 24)
| ((value & 0xff00) << 8)
| ((value & 0x00ff0000) >> 8)
| ((value & 0xff000000) >> 24);
return BitConverter.GetBytes(value);
For a general purpose solution you should create a class and split the example into separate methods to extract the data and write the values (integers, strings).
Regards, Elmar -
Converting ASCII text (byte array ending in null) to a String
Hi all,
I am trying to convert a null terminated ascii string stored in a byte array to a java String. When I pass the byte array to the String constructor it
does not detect/interpret the null as a terminator for the ascii string. Is this something I have to manually program in? ie Check for where the null is and then
pass that subarray of everything before the null to the String constructor?
example of problem
// A B C D null F (note F is junk in the array, and should be ignored since it is after null)
byte[] asciiArray = { 65, 66, 67, 68, 0, 70 };
System.out.println(new String(asciiArray, "UTF-8"));
//this prints ABCD"sqare icon"FWhy do you expect the null character to terminate the string? If you come from a C or C++ background, you need to understand that java.lang.String is not just a mere character array. It's a full-fledged Java object that knows its length without having any need for null terminator. So Ascii 0 is just another character for String object. To achieve what you want to do, you have to manually loop through the byte array and stop when you encounter a null character.
-
How do I read directly from file into byte array
I am reading an image from a file into a BuffertedImage then writing it out again into an array of bytes which I store and use later on in the program. Currently Im doing this in two stages is there a way to do it it one go to speed things up.
try
//Read File Contents into a Buffered Image
/** BUG 4705399: There was a problem with some jpegs taking ages to load turns out to be
* (at least partially) a problem with non-standard colour models, which is why we set the
* destination colour model. The side effect should be standard colour model in subsequent reading.
BufferedImage bi = null;
ImageReader ir = null;
ImageInputStream stream = ImageIO.createImageInputStream(new File(path));
final Iterator i = ImageIO.getImageReaders(stream);
if (i.hasNext())
ir = (ImageReader) i.next();
ir.setInput(stream);
ImageReadParam param = ir.getDefaultReadParam();
ImageTypeSpecifier typeToUse = null;
for (Iterator i2 = ir.getImageTypes(0); i2.hasNext();)
ImageTypeSpecifier type = (ImageTypeSpecifier) i2.next();
if (type.getColorModel().getColorSpace().isCS_sRGB())
typeToUse = type;
if (typeToUse != null)
param.setDestinationType(typeToUse);
bi = ir.read(0, param);
//ir.dispose(); seem to reference this in write
//stream.close();
//Write Buffered Image to Byte ArrayOutput Stream
if (bi != null)
//Convert to byte array
final ByteArrayOutputStream output = new ByteArrayOutputStream();
//Try and find corresponding writer for reader but if not possible
//we use JPG (which is always installed) instead.
final ImageWriter iw = ImageIO.getImageWriter(ir);
if (iw != null)
if (ImageIO.write(bi, ir.getFormatName(), new DataOutputStream(output)) == false)
MainWindow.logger.warning("Unable to Write Image");
else
if (ImageIO.write(bi, "JPG", new DataOutputStream(output)) == false)
MainWindow.logger.warning("Warning Unable to Write Image as JPEG");
//Add to image list
final byte[] imageData = output.toByteArray();
Images.addImage(imageData);
If you don't need to manipulate the image in any way I would suggest you just read the image file directly into a byte array (without ImageReader) and then create the BufferedImage from that byte array.
-
How do I get a byte array from an object passed into the JNI?
This is what my java code looks like:
public class streamedData
protected byte[] m_value = null;
public byte[] getByteArray ()
return m_value;
/* code not pertaining to this question snipped. */
jclass streamedDataClass = env->GetObjectClass(jstreamedData);
// Get methodIDs for the various NPKI_Extension methods
value = env->GetMethodID(streamedDataClass, "getByteArray", "()[B");
lstreamedData->value = (unsigned char *)malloc (lstreamedData->length);
if (lstreamedData->value == NULL)
return INSUFFICIENT_MEMORY;
memset (lstreamedData->value, 0, lstreamedData->length);
memcpy (lstreamedData->value, env->CallByteMethodA(streamedDataClass, value, NULL), lstreamedData->length);
This is not working.
My question is, how do I get a copy of or read m_value in the JNI layer? Do I have to make the byte array public and access it as a field ID?
Any help would be appreciated. Why oh why can't there be a CallByteArrayMethod????My question is, how do I get a copy of or read m_value in the JNI layer? Do I have to make the byte array public and access it as a field ID?
You can retrieve a handle to the byte array, through a method call, as you're doing now, or by directly accessing it through GetFieldID.
In the case of the method call, you'll want to do:jmethodID getByteArrayMethod = env->GetMethodID(streamedDataClass, "getByteArray", "()[B");
jbyteArray byteArray = static_cast<jbyteArray>( env->CallObjectMethod( jstreamedData, getByteArrayMethod ) );In the case of field access, you can do:jfieldID m_valueFieldID = env->GetFieldID( streamedDataClass, "m_value", "[B" );
jbyteArray byteArray = static_cast<jbyteArray>( env->GetObjectField( jstreamedData, m_valueFieldID ) );Once you have byteArray, you need to access it using the array operations:lstreamedData->value = env->GetByteArrayElements( byteArray, 0 );
// Do what you want to do, then release the array
env->ReleaseByteArrayElements( byteArray, lstreamedData->value, 0 );As always, Jace, http://jace.reyelts.com/jace, makes this easier. For example,void printByteArray( jobject jstreamedData ) {
streamedData data( jstreamedData );
JArray<JByte> byteArray = streamedData.m_value();
for ( int i = 0; i < byteArray.length(); ++i ) {
cout << byteArray[ i ];
}God bless,
-Toby Reyelts -
How do I store an Int, a short, and multiple bytes from file in byte array
I'm attempting to do this for a project but can't figure out how to store the three values in one byte array. This is what i've tried
public void send(byte[] input)
// TODO
ByteArrayInputStream bais = new ByteArrayInputStream(input);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
byte[] pData = new byte[100];
try {
dos.writeShort(checkSum);
dos.writeInt(nextSeqNum);
pData=baos.toByteArray();
bais.read(pData);
} catch (IOException e) {
DatagramPacket dgp = new DatagramPacket(pData, pData.length);When i set pData=baos.toByteArray() it changes the size and then stops me from being able to read the other 94 bytes into the array to send. Any ideas?You don't need the ByteArrayInputStream at all.
dos.writeShort(checkSum);
dos.writeInt(nextSeqNum);
dos.write(input);
pData = baos.toByteArray();
When i set pData=baos.toByteArray() it changes the sizeNo, it makes it refer to a new byte[] array containing what you've written to the BAOS. That's what it's supposed to do. -
How to get a string or byte array representation of an Image/BufferedImage?
I have a java.awt.Image object that I want to transfer to a server application (.NET) through a http post request.
To do that I would like to encode the Image to jpeg format and convert it to a string or byte array to be able to send it in a way that the receiver application (.NET) could handle. So, I've tried to do like this.
private void send(Image image) {
int width = image.getWidth(null);
int height = image.getHeight(null);
try {
BufferedImage buffImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
ImageIcon imageIcon = new ImageIcon(image);
ImageObserver observer = imageIcon.getImageObserver();
buffImage.getGraphics().setColor(new Color(255, 255, 255));
buffImage.getGraphics().fillRect(0, 0, width, height);
buffImage.getGraphics().drawImage(imageIcon.getImage(), 0, 0, observer);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(stream);
jpeg.encode(buffImage);
URL url = new URL(/* my url... */);
URLConnection connection = url.openConnection();
String boundary = "--------" + Long.toHexString(System.currentTimeMillis());
connection.setRequestProperty("method", "POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
String output = "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"myImage\"; filename=\"myFilename.jpg\"\r\n"
+ "Content-Type: image/jpeg\r\n"
+ "Content-Transfer-Encoding: base64\r\n\r\n"
+ new String(stream.toByteArray())
+ "\r\n--" + boundary + "--\r\n";
connection.setDoOutput(true);
connection.getOutputStream().write(output.getBytes());
connection.connect();
} catch {
}This code works, but the image I get when I save it from the receiver application is distorted. The width and height is correct, but the content and colors are really weird. I tried to set different image types (first line inside the try-block), and this gave me different distorsions, but no image type gave me the correct image.
Maybe I should say that I can display the original Image object on screen correctly.
I also realized that the Image object is an instance of BufferedImage, so I thought I could skip the first six lines inside the try-block, but that doesn't help. This way I don't have to set the image type in the constructor, but the result still is color distorted.
Any ideas on how to get from an Image/BufferedImage to a string or byte array representation of the image in jpeg format?Here you go:
private static void send(BufferedImage image) throws Exception
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(image, "jpeg", byteArrayOutputStream);
byte[] imageByteArray = byteArrayOutputStream.toByteArray();
URL url = new URL("http://<host>:<port>");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStream outputStream = connection.getOutputStream();
outputStream.write(imageByteArray, 0, imageByteArray.length);
outputStream.close();
connection.connect();
// alternative to connect is to get & close the input stream
// connection.getInputStream().close();
}
Maybe you are looking for
-
Hi, I am setting up a new heirarchy in Business level RPD, and in the new "Dimensions", the tab "Tables" is disabled, i tried opening it in both online as well as offline mode, same issue. When I add a new "Logical Level" object under it, the "Add" c
-
To launch Logic directly opening a song: it doesn't find the doc and opens the template song
On Lion 10.7.2 it happens regularly. It didn't happen in SL. Any solution? f
-
My itouch screen froze showing "plug to itunes" after trying to update to iOS6. It still can be turned on and off. But the screen froze showing that message. I perhaps need to restore it. But is there any ways to export all the pictures from it befor
-
Hello, Can we do a secure FTP using ABAP code ?? Thanks John
-
Quick and Easy WiFi vs. 3G Question
Hi, I am just wondering what the difference in terms of performance is between WiFi and 3G. I have unlimited 3G usage, but if I find myself in a location that has free WiFi, is there any advantage to using the WiFi for iPhone internet browsing? Is Wi