CONVERT 4 bytes WCHAR_T in SOLARIS COMPILER TO UNSIGNED SHORTTO

All,
Do you guys know any code or function that could convert 4-bytes wchar_t string literal (Solaris defined 4 bytes for wchar_t) to array of unsigned short?

Unlike MSFT Windows VC++/C#/VB where you will get UCS-2/UTF-32 when your program has UNICODE macro defined at the start of your source program, POSIX defines wchart as an opaque data type.
Solaris is a POSIX system and thus we treat the wchar_t also as an opaque data type that can be different from one locale to another.
(We didn't have Unicode or at least it wasn't that popular when there was wchar_t data type and intefaces first created and also implemented at various Unix systems even though Sun was a founding member company of the Unicode consortium.)
We though guarantee that the wchar_t will be in UTF-32 for all Solaris Unicode/UTF-8 locales.
Hence, to have proper conversions between any codeset/codepage or the codeset of the current locale, i.e., nl_langinfo(CODESET), and UTF-32 or UCS-4, please use iconv(3C), iconv(1), or sdtconvtool(1) and such conversion interfaces. By the way, UCS-4 is being obsoleted and so using of UTF-32 is recommended.
The iconv code conversions between UTF-32 and any other codesets in Solaris will also screen out any illegal characters or byte sequences as specified in the latest Unicode Standard and UTF-8 Corrigendum at Uniocde 3.1 and 3.2.

Similar Messages

  • Converting a byte[] back to key problem

    I CAN create a key and convert the key to a byte array, then convert the array to a string(base 64):
    KeyGenerator generator = KeyGenerator.getInstance("DES");
    generator.init(new SecureRandom());
    key = generator.generateKey();
    byte[] keyBytes = key.getEncoded;
    BASE64Encoder encoder = new BASE64Encoder();
    String randomKey = encoder.encode(keyBytes);
    and I CAN save that string to a database, forget about it, then sometime later reload it and convert it to a byte array again:
    String loadedKey = "WhAt3Ver-It-I5" //from DB
    BASE64Decoder decoder = new BASE64Decoder();
    byte[] loadedKeyBytes = decoder.decodeBuffer(loadedKey);
    what I CAN'T do is convert the loadedKeyBytes back into the key of the same type as it was originally, enabling me to decrypt whatever that key originally encrypted.
    Does anyone know.
    I know I need to convert it to a KeySpec, I presume as:
    DESKeySpec keySpec = new DESKeySpec(loadedKeyBytes);
    this compiles correctly.... but how do i then recreate the key so i can use it for decryption.
    Once i've finished this test program I should be able to port it to my application.
    Many thanks in advance guys!
    Cheers!
    Relisys
    ================ CODE FOLLOWS ======================
    import java.io.*;
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import com.sun.crypto.provider.SunJCE;
    import sun.misc.*;
    public class SecPrescrip {
    public static void main(String[] args) throws Exception {
    // Create Key.
    Key key;
    KeyGenerator generator = KeyGenerator.getInstance("DES");
    generator.init(new SecureRandom());
    key = generator.generateKey();
    // Get a cipher object
    Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    // Encrypt the input string:
    cipher.init(Cipher.ENCRYPT_MODE, key);
    String input = "Medicare Secure Prescription: 30 Tamazopan 200mg tablets. Dosage: 1 to be taken every 4 hours";
    System.out.println("Stage 1: ENCRYPT PRESCRIPTION WITH A RANDOM DES KEY");
    System.out.println("===================================================");
    System.out.println(" - Input Plain Text: "+input);
    System.out.println("");
    byte[] stringBytes = input.getBytes("UTF8");
    byte[] raw = cipher.doFinal(stringBytes);
    BASE64Encoder encoder = new BASE64Encoder();
    String ciphertext1 = encoder.encode(raw);
    System.out.println(" - Cipher Text: "+ciphertext1);
    System.out.println("");
    byte[] keybytes = key.getEncoded();
    String randomkey = encoder.encode(keybytes);
    System.out.println(" - Random Prescription Key: "+randomkey);
    System.out.println("");
    System.out.println("ENCRYPTION SUCESSFULL");
    System.out.println("");
    System.out.println("");
    System.out.println("Stage 2: ENCRYPT RANDOM KEY WITH PATIENT MEDICARE KEY");
    System.out.println("=====================================================");
    BASE64Decoder decoder = new BASE64Decoder();
    String passphrase = "ABCD1234efghIJ56"; //Patient Medicare Key
    System.out.println(" - Patient Medicare Key: "+passphrase);
    System.out.println("");
    System.out.println(" - Input Plain Text: "+randomkey);
    String algorithm = "PBEWithMD5AndDES";
    byte[] salt = new byte[8];
    int iteration = 20;
    KeySpec ks = new PBEKeySpec(passphrase.toCharArray());
    SecretKeyFactory skf = SecretKeyFactory.getInstance(algorithm);
    SecretKey key2 = skf.generateSecret(ks);
    byte[] input2 = decoder.decodeBuffer(randomkey);
    MessageDigest md = MessageDigest.getInstance("MD5");
    md.update(passphrase.getBytes());
    md.update(input2);
    byte[] digest = md.digest();
    System.arraycopy(digest, 0, salt, 0, 8);
    AlgorithmParameterSpec aps = new PBEParameterSpec(salt, iteration);
    cipher = Cipher.getInstance(algorithm);
    cipher.init(Cipher.ENCRYPT_MODE, key2, aps);
    byte[] outputFinalKey = cipher.doFinal(input2);
    String ciphertext2 = encoder.encode(outputFinalKey);
    String saltString = encoder.encode(salt);
    String encryptedCiphertext = saltString+ciphertext2;
    System.out.println("");
    System.out.println(" - Cipher Text (Final Prescription Key): "+ciphertext2);
    System.out.println("");
    System.out.println(" - Salt: "+saltString);
    System.out.println("");
    System.out.println(" - Full Encrypted Output: "+encryptedCiphertext);
    System.out.println("");
    System.out.println("ENCRYPTION SUCESSFULL");
    System.out.println("");
    System.out.println("");
    System.out.println("Stage 3: DECRYPT PRESCRIPTION KEY USING PATIENT MEDICARE KEY");
    System.out.println("============================================================");
    //NOT CHANGED String passphrase = "ABCD1234efghIJ56";
    System.out.println(" - Patient Medicare Key: "+passphrase);
    System.out.println("");
    System.out.println(" - Input Plain Text: "+ciphertext2);
    algorithm = "PBEWithMD5AndDES";
    salt = new byte[8];
    iteration = 20;
    ks = new PBEKeySpec(passphrase.toCharArray());
    skf = SecretKeyFactory.getInstance(algorithm);
    SecretKey key3 = skf.generateSecret(ks);
    //Load in the input bytes as if they had been loaded from an sql database or the like
    String saltIn = encryptedCiphertext.substring(0,12);
    String ciphertext3 = encryptedCiphertext.substring(12,encryptedCiphertext.length());
    byte[] saltArray = decoder.decodeBuffer(saltIn);
    byte[] ciphertextarray = decoder.decodeBuffer(ciphertext3);
    aps = new PBEParameterSpec(saltArray, iteration);
    cipher = Cipher.getInstance(algorithm);
    cipher.init(Cipher.DECRYPT_MODE, key3, aps);
    byte[] outputKey2 = cipher.doFinal(ciphertextarray);
    String plaintext2 = encoder.encode(outputKey2);
    System.out.println(" - Plain Text (Random Generated Key): "+plaintext2);
    System.out.println("");
    System.out.println("");
    System.out.println("ENCRYPTION SUCESSFULL");
    System.out.println("");
    System.out.println("");
    System.out.println("Stage 4: DECRYPT PRESCRIPTION KEY USING PATIENT MEDICARE KEY");
    System.out.println("============================================================");
    // The decrypter string plaintext should be the same as the BASE64 Encoded representation of the random DES string
    byte[] randomKeyFetched = decoder.decodeBuffer(plaintext2);
    generator = KeyGenerator.getInstance("DES");
    DESKeySpec keyspec = new DESKeySpec(randomKeyFetched);
    * Stuck here! Once the key is reformed it will be complete!
    }

    You need to use a SecretKeyFactory to convert the byte array back to a SecretKey to use in decryption. Continuing your example:
    SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
    DESKeySpec desKeySpec = new DESKeySpec(loadedKeyBytes);
    SecretKey sk = skf.generateSecret(desKeySpec);
    Use sk in the call to the Cipher init() function. (Note that you don't call KeyGenerator to restore a key from its bytes.)
    Incidently, if you're using ECB mode for encryption I don't think you need to worry about the Initialization Vector. However, if you're using CBC mode (which is the default DES mode for the default SunJCE provider), I believe you also have to make sure that the decryption system starts from the same Initialization Vector that was used for encryption. To deal with this, if 'cipher' is your encryption Cipher object, then you call
    byte bytIV[] = cipher.getIV();
    to get the 8-byte IV array. To decrypt, you need to call:
    IvParameterSpec iv = new IvParameterSpec(bytIV);
    This is an AlgorithmParameterSpec, and can be used as the third argument to the init() function for Cipher to set up decryption, e.g.
    Cipher cd = Cipher.getInstance("DES/ECB/PKCS5Padding");
    cd.init(Cipher.DECRYPT_MODE, sk, iv);
    I believe that CBC mode is more secure than ECB mode when you have more than 8 bytes of material to encode (e.g. use "DES/CBC/PKCS5Padding"
    when you create the Cipher objects).
    To simplify things a bit, you might just want to use a fixed 8-byte Initialization Vector by constructing a IvParameterSpec and using it for all DES encryption and decryption.
    The documentation on all of this is extraodinarily obscure.

  • Convertion of byte array in UTF-8 to GSM character set.

    I want to convert byte array in UTF-8 to GSM character set. Please advice How can I do that?

    String s = new String(byteArrayInUTF8,"utf-8");This will convert your byte array to a Java UNICODE UTF-16 encoded String on the assumption that the byte array represents characters encoded as utf-8.
    I don't understand what GSM characters are so someone else will have to help you with the second part.

  • FM to convert double byte chars

    Hi All,
    Is there anyone know what are the function module to convert double-byte chars? Thanks.

    Seems like Blue Sky is not clear
    You want to convert what into what?
    Whats the purpose of this requirement, kindly give more details.
    Regards
    Karthik D

  • How Convert a Byte array to a image format

    Hi,
    How to convert a Byte array to an image format....I shall be more clear what i want...See i recieve a Byte array fom server this Byte array before recieveing at my end it was converted from an image/text format into a Byte array and is sent from server and, I recieve this Byte array now I have to convert this Byte array into their respective image....please tell me how to convert a Byte array to a image ......... Kindly explain clearly as i am new to Java......
    Thanking You.

    Note: This thread was originally posted in the [New To Java|http://forums.sun.com/forum.jspa?forumID=54] forum, but moved to this forum for closer topic alignment.

  • Converting a byte[] into a char[]

    Hi All,
    what's the best way to convert a byte[] into a char[]?
    Any advice appreciated. Thanks in advance.

    you will need a encoding schema...
    byte is binary data, char is interpret from byte by the system...
    easiest way without extra coding...
    new String(byte[], encoding).toCharArray()
    if you don't specify encoding... system default is used.

  • Converting a byte to an integer

    Hi,
    I want to convert a byte[] variable called 'rgb' to an integer value. when i looked through the api, i found intValue() could do so i included the statement
    int num = rbg.intValue();but it gives me a error. how can i convert the byte[] value to an integer. any suggestion, i am new to Java programming.
    Thanks in advance

    It would help if you showed a little more of your code--like what rbg is for instance--and if you pasted in the exact error message.
    What class was intValue in? You mean the one in the Byte class? That's a method that you call on a Byte object, not a byte[] .

  • Converting a byte[] to a int or a Point

    I have sent a DatagramPacket containing a Point object converted to a byte[]. Now I want to convert the byte[] object back to a Point object. How do I do it?
    In my application I want to draw a number of dots in a window, send to a copy of the application in some other location on the Net and the two applications must view the same dots in real time. So I thought I would draw the dots, send the cordinats in a Datagram and then draw the dots using this cordinats. Is that a good idea?
    Best regards
    Jonas

    To create a Point from a byte[], assuming the byte[] has two elements:
    Point p = new Point((int)byte[0], (int)byte[1]);Is that what you need?

  • Convert a byte/Byte - HEX STRING ?

    Hi ,
    My Problem is , I want to convert a byte/Byte value to hex string. If there is any way to convert bytes to hex strings then please tell me.
    please help me.

    Integer.toHexString(byteValue);
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Integer.html

  • Convert a string to an array of 16bit unsigned integers

    I have a string represented in hex format, how can I convert this to an array of 16 bit unsigned integers?
    I know I can use string to byte array to easily convert it to 8 but unsigned integers, is there a simple way for 16 bit unsigned integers?
    Solved!
    Go to Solution.

    hydzik wrote:
    I have a string represented in hex format, how can I convert this to an array of 16 bit unsigned integers?
    I know I can use string to byte array to easily convert it to 8 but unsigned integers, is there a simple way for 16 bit unsigned integers?
    While your description is somewhat vague and not very clear, I think the typecast solution from the previous poster may not be what you look for. You may more likely look for something along these lines:
    Rolf Kalbermatter
    CIT Engineering Netherlands
    a division of Test & Measurement Solutions
    Attachments:
    HexToU16.png ‏17 KB

  • How to convert ufs to zfs in Solaris 10

    After installinng solaris 10 i wnat to convert my ufs to zfs , how can i do that , unfortunately tehre is no documentation available in docs.sun.com. any help is greatly appreciated

    I found a document on Sun site long time ago titled "The best file system in the world" (Peter Baer Galvin's as far as I remember). I believe it can be still found somewhere there, and here are some of citations that may be helpful:
    There are many things that ZFS is, currently, and a few that it is not. The most frustrating current limit is that ZFS cannot be the root file system. A project is underway to resolve that issue, however. It certainly would be nice to install a system with ZFS as the root file system and then to have features like snapshots available for systems work. Consider taking a snapshot, making a change that causes a problem on the system (e.g., installing a bad patch), and then reverting the system to its pre-patch state by restoring the snapshot.
    Also, ZFS can be imported and exported, but it is not a true "clustered file system" in that only one host can access the file system at one time.
    An open issue is the support of ISVs, such as Oracle, for the use of a ZFS file system to store their data. I'm sure this will come over time.
    Hot spares are not implemented currently. If a disk fails, a zpool replace command must be executed for the bad disk to be replaced by a good one.
    A mirror can be removed from a mirror pair by the zpool detach command, but RAID-Z sets and non-mirrored disks currently cannot be removed from a pool.
    Also, currently there is no built-in encryption, and at this point ZFS is a Solaris-only feature. Whether ports will be done to other operating systems remains to be seen.
    Just a brief word on the readiness of ZFS for production use. Usually, a new file system would not even be considered for production use for quite a while after its first ship. ZFS, on the other hand, may well garner production use immediately on its production ship. The testing that has gone into ZFS is astounding, and in fact testing was considered a first-class component of the ZFS design and implementation.
    More on it: http://www.opensolaris.org/os/community/zfs/docs/
    HTH, Rev

  • Convert binary bytes to Labview Extended Precision type

    Hello All:
    I am reading a binary file that was written in Windows. One of the types used in the data structure
    is the Delphi extended precision type, which is 10 bytes. When reading this in using Labview's
    "read binary file" VI, there is only one choice, and that is to read it in as an array of 10 bytes
    (Labview's extended precision is 16 bytes.) I have tried using the type cast with no results.
    So....how to convert the data in the 10 byte array to a 16 byte extended precision format in
    Labview? I guess part of the problem is not really understanding how the extended precision
     type is stored in IEEE format.
    Has anyone performed this conversion before that could help out? I'm sure this must have
    been done by someone....somewhere....I have no hair left....
    Any help would be appreciated!
    Thanks,
    Gary.

    Uhm, something must have gone wrong, the link TST sent,
    mentions that LabVIEW stores extended data as 80 bit (10 bytes) on Intel platform.
    Complex double is stored as two doubles (=16 byes). My guess is that Altenbach's latest note mentioning the endianess should help you.
    If the endiannes is right you should be able to just typecast the data:
    Free Code Capture Tool! Version 2.1.3 with comments, web-upload, back-save and snippets!
    Nederlandse LabVIEW user groep www.lvug.nl
    My LabVIEW Ideas
    LabVIEW, programming like it should be!

  • Convert.To​Byte and logical masks, from VB to LabVIEW

    Hi guys,
    I have to write a VI communicating via RS232 with a microcontroller for a PWM application. A colleague has given me the GUI he has developpd in VB and I would like to integrate it into my LabVIEW programme by converting the VB code into Labview code.  Here's the code:
    Private Sub LoadButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles loadButton.Click
            Dim bufLen As Integer = 12      // Buffer length
            Dim freq As Integer = 0      // frequency
            Dim pWidth As Integer = 0      // pulse width
            Dim dac As Integer = 0       // Value used in oscillator setting for generating pulse frequency
            Dim addr As Integer = 0      // Address of the pulse width in the pulse generator.
            Dim rTime As Integer = 0      // duration of machining/pulse train in ms.
            Dim returnValue As Byte = 0      // A variable for storing the value returned by the 
                                                           //microcontroller after it receives some data
            Dim buffer(bufLen) As Byte       // creates an array of bytes with 12 cells => buffer size = 8 x12 = 96 bits
    // can you explain a bit please I know you're converting the entered values into byte and put them one by one in a specific order. This order is how the 
    //microcontroller expects them
                addr = (Floor((pWidth - Tinh) / Tinc)) // Formula from hardware, calculates address setting for pulse generator to set pulse width.
                buffer(0) = Convert.ToByte(Floor(3.322 * (Log10(freq / 1039)))) // Caluclates OCT value for use in setting oscillator for pulse freq.
                dac = (Round(2048 - ((2078 * (2 ^ (10 + buffer(0)))) / freq)))  // Calculates DAC value for use in setting oscillator for pulse freq.
                buffer(1) = Convert.ToByte((dac And &HF00) >> 8)                         //
    // &H is the vb.net to tell it its hex code, F00 gives the top 4 bits from a 12 bit value.
                buffer(2) = Convert.ToByte(dac And &HFF) // For values that are larger than 256 (8bits) the value needs to be split across 2 bytes (16 bits) this gets the //bottom 8 bits.  &H is the vb.net to tell it its Hex.
                buffer(3) = Convert.ToByte((addr And &HFF0000) >> 16) // This value may be so large it requires 3 bytes (24bits). This gets the top 8 bits.
                buffer(4) = Convert.ToByte((addr And &HFF00) >> 8) // This gets the middle 8 bits.
                buffer(5) = Convert.ToByte(addr And &HFF)// This gets the bottom 8 bits.
                buffer(6) = Convert.ToByte((rTime And &HFF0000) >> 16) //This value may also be 3 bytes long.
                buffer(7) = Convert.ToByte((rTime And &HFF00) >> 8)
                buffer(8) = Convert.ToByte(rTime And &HFF)
                buffer(9) = Convert.ToByte(2.56 * ocpBox.Value)  // The ocp pulse period is formed of 256 steps or counts, so if a percentage is requested, this formula gives the number of steps/counts required to set the pulse width
                buffer(10) = Convert.ToByte(tempBox.Value)
                If (tempCheck.Checked = True) Then
                    buffer(11) = 1
                Else
                    buffer(11) = 0
                End If
                freq = ((2 ^ buffer(0)) * (2078 / (2 - (dac / 1024))))
                pWidth = Tinh + ((((Convert.ToInt32(buffer(3))) << 16) Or ((Convert.ToInt32(buffer(4))) << 8) Or (Convert.ToInt32(buffer(5)))) * Tinc)
                ' Connect to device
                serialPort1.Write(1) // Sends the number 1. This tells the microcontroller we are about to start sending data. It should respond with a zero if it is ready 
                                             //and the connection is good.
    The line "serialPort1.Write(buffer, 0, bufLen)" sends the buffered data where the variables are: buffer =  the buffered data; 0 = the position in the buffer to start from; bufLen = the position in the buffer to stop sending data.
    What's the best way to deal with the Convert.ToBytes and the logical masks And ??
    Thanks in advance for your time and consideration,
    regards
    Alex
    Solved!
    Go to Solution.

    Try this
    Beginner? Try LabVIEW Basics
    Sharing bits of code? Try Snippets or LAVA Code Capture Tool
    Have you tried Quick Drop?, Visit QD Community.

  • HowTO: convert Image- byte[] when don't know image format?

    I have byte[] field in my DB. Images have been stored there.
    Images can be jpg/gif/png.
    My task is to scale them and save back (to another field)
    I have such code:
    I know, that getScaledInstance is bad, but please, don't pay attention. This operation +(massive image resizing will be performed once a year at night)+
    public class ImageResizer {
         private static byte[] resizeImage(byte[] sourceImg, int newWidth){
              byte[] result = null;
              Image resizedImage = null;     //output image
              ImageIcon imageIcon = new ImageIcon(sourceImg);     //source image
              Image imageSource = imageIcon.getImage();
              int imageSourceWidth = imageSource.getWidth(null);
              int imageSourceHeight = imageSource.getHeight(null);
              if(imageSourceWidth > newWidth){
                   float scaleFactor =  newWidth/imageSourceWidth;
                   int newHeight = Math.round(imageSourceHeight*scaleFactor);
                 resizedImage = imageSource.getScaledInstance(newWidth, newHeight,Image.SCALE_SMOOTH);
                 Image temp = new ImageIcon(resizedImage).getImage();// This code ensures that all the pixels in the image are loaded.
                 // Create the buffered image.
                 BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null),BufferedImage.TYPE_INT_RGB);
                 /**And what next?*/
              }else{
                   result = sourceImg;
              return result;
         public static byte[] scaleToSmall(byte[] sourceImg){
              return resizeImage(sourceImg, 42);
         public static byte[] scaleToBig(byte[] sourceImg){
              return resizeImage(sourceImg, 150);
         public static byte[] serializeObjectToBytearray(Object o) {
             byte[] array;
             try {
               ByteArrayOutputStream baos = new ByteArrayOutputStream();
               ObjectOutputStream oos = new ObjectOutputStream(baos);
               oos.writeObject(o);
               array = baos.toByteArray();
             catch (IOException ioe) {
               ioe.printStackTrace();
               return null;
             return array;
    }On this forum I've found many solutions, but approximately all of them suppose that I know file format (PixelGrabber, ImageIO, e.t.c). But I don't know it. I know, that it can be jpeg/gif/png.
    What can I do?
    I've found that simple serialization can help me (+public static byte[] serializeObjectToBytearray(Object o)+), but seems like it doesn't work.
    Edited by: Holod on 01.11.2008 10:18

    Here I came up with one possible solution using some more functionality of ImageIO.
    public class ImageResizer {
        private static byte[] resizeImage(byte[] sourceBytes, int newWidth) throws Exception {
            byte[] scaledBytes;
            // ImageIO works with Files or Streams, so convert byte[] to stream
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(sourceBytes);
            // Why not just use ImageIO.read(inputStream)? - Because there would be
            // no way to know the original image format (I am assuming here that
            // you need to write back the image in the same format as the original)
            ImageInputStream imageInputStream = ImageIO.createImageInputStream(byteArrayInputStream);
            // assuming there is at least one ImageReader able to read the image
            ImageReader imageReader = ImageIO.getImageReaders(imageInputStream).next();
            // save image format name so we can write it back in the same format
            String formatName = imageReader.getFormatName();
            imageReader.setInput(imageInputStream);
            BufferedImage sourceImage = imageReader.read(0);
            int imageSourceWidth = sourceImage.getWidth();
            int imageSourceHeight = sourceImage.getHeight();
            if (imageSourceWidth > newWidth) {
                // be careful with integer divisions ( 500 / 1000 = 0!)
                double scaleFactor = (double) newWidth / (double) imageSourceWidth;
                int newHeight = (int) Math.round(imageSourceHeight * scaleFactor);
                System.out.println("newWidth=" + newWidth + ", newHeight=" + newHeight + ", formatName=" + formatName);
                // getScaledInstance provides the best downscaling quality but is
                // orders of magnitude slower than the alternatives
                // since you're saying performance is not issue, I leave it as is
                Image scaledImage = sourceImage.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
                // Unfortunately we need a RenderedImage to use ImageIO.write.
                // So the next lines convert whatever type of Image was returned
                // by getScaledImage into a BufferedImage.
                // Using TYPE_INT_ARGB so potential alpha channels are preserved
                BufferedImage scaledBufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
                Graphics2D g2 = scaledBufferedImage.createGraphics();
                g2.drawImage(scaledImage, 0, 0, null);
                g2.dispose();
                // Now use ImageIO.write to encode the image back into a byte[],
                // using the same image format
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                ImageIO.write(scaledBufferedImage, formatName, byteArrayOutputStream);
                scaledBytes = byteArrayOutputStream.toByteArray();
            } else {
                // if not scaling happened, just return the original byte[]
                scaledBytes = sourceBytes;
            return scaledBytes;
        public static void main(String[] args) throws Exception {
            // this is just for my own local testing
            // simulate byte[] input from database
            BufferedImage image = ImageIO.read(new File("input.jpg"));
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "PNG", byteArrayOutputStream);
            byte[] sourceBytes = byteArrayOutputStream.toByteArray();
            byte[] scaledBytes = resizeImage(sourceBytes, 640);
            // write out again to check result
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(scaledBytes);
            image = ImageIO.read(byteArrayInputStream);
            ImageIO.write(image, "PNG", new File("output.jpg"));
    }

  • Forte 62, Solaris Compiler error with purify

    Hi all;
    I am using a Solaris 2.8 machine, a Forte62 compiler in 64 bit mode.
    I have set all LD_LIBRARY_PATH up and it compiles most my code till it gets to the part that it purifies. It gives me this error:
    ld: fatal: relocation error: R_SPARC_DISP64: file /purifycache/vob/tools_SunOS/Forte6U2/WS6U2/lib/v9/crti_pure_p3_c0_111202109_64.o: symbol exshared0: offset 0xffffffff7a6faeb4 is non-aligned
    Any ideas on what is causing this?
    Thanks a mill
    Ter

    The problem appears to be in purify code. You should contact their tech support.

Maybe you are looking for

  • My iphone 4s having problm after i updated to ios 8

    i upgraded to ios 8 but it became problm for me pgone getting slow crushing of applications

  • My iPhoto keeps freezing everytime i go into Preferences in the Menu

    I want to change some options but it just freezez every time. I have restarted the Mac, even rebuilt the Library. Not sure what the problem is what I can do. I am able to browse through my pictures no problem. Any help greatly appreciated.

  • Search in SharePoint 2013 with Oracle as external DB

    hello experts... i want to create a custom search page with intellisense enable text box and button to search Oracle DB as external content. from where can i start? i googled a bit and get the following link as start up. http://lightningtools.com/bcs

  • How do I achive this dotted effect

    http://www.istockphoto.com/file_download_approved.php?RequestExtendedLicense=0&quantity_34 =1&quantity_35=1&quantity_36=1&quantity_37=1&quantity_38=1&quantity_39=1&quantity_40=1&IAg ree=&fileID=3781774&ConcreteTypeID=8&inPoint=0&outPoint=0&action=acc

  • Can someone send me the Camera Raw 8.6 plugin?

    It happens every time there's an ACR update. Lightroom installs its own (secretly held) version. Lightroom starts complaining that Pshop does not have the latest plugin. Meanwhile, neither Photoshop nor its Update menu item nor Adobe Application Mana