How to cast BufferedImage to RichImage

Hi,
I have an image of type BufferedImage. How can I show to the user at run time ?. I thought that I can do it using RichImage component but I am facing problem in casting.
I am using Jdeveloper 12c the page is jsf
Thanks
Ahmad

Dear Ahmad,
Use below code its tested in my machine.
import java.io.IOException;
import sun.misc.BASE64Encoder;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import oracle.adf.view.rich.component.rich.input.RichInputText;
public class MainTester2 {
    private RichInputText rimg;
    public void setRimg(RichInputText rimg) {
        this.rimg = rimg;
    public RichInputText getRimg() {
        return rimg;
     * Maroof!
     * Encode image to string
     * @param image The image to encode
     * @param type jpeg, bmp, ...
     * @return encoded string
    public static String encodeToString(BufferedImage image, String type) {
        String imageString = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, type, bos);
            byte[] imageBytes = bos.toByteArray();
            BASE64Encoder encoder = new BASE64Encoder();
            imageString = encoder.encode(imageBytes);
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        return imageString;
    public static void main (String args[]) throws IOException { 
        /* Test image to string and string to image start */
        BufferedImage img = ImageIO.read(new File("C:\\Users\\maroof\\Downloads\\TR3.jpg"));
        BufferedImage newImg;
        String imgstr;
        imgstr = encodeToString(img, "png");
        System.out.println(imgstr);
        RichInputText imgTxt = new RichInputText();
        imgTxt.setValue(imgstr);
        System.out.println("Out of new == "+imgTxt.getValue().toString());
Maroof

Similar Messages

  • How to cast an Object into a specific type (Integer/String) at runtime

    Problem:
    How to cast an Object into a specific type (Integer/String) at runtime, where type is not known at compile time.
    Example:
    public class TestCode {
         public static Object func1()
    Integer i = new Integer(10); //or String str = new String("abc");
    Object temp= i; //or Object temp= str;
    return temp;
         public static void func2(Integer param1)
              //Performing some stuff
         public static void main(String args[])
         Object obj = func1();
    //cast obj into Integer at run time
         func2(Integer);
    Description:
    In example, func1() will be called first which will return an object. Returned object refer to an Integer object or an String object. Now at run time, I want to cast this object to the class its referring to (Integer or String).
    For e.g., if returned object is referring to Integer then cast that object into Integer and call func2() by passing Integer object.

    GDS123 wrote:
    Problem:
    How to cast an Object into a specific type (Integer/String) at runtime, where type is not known at compile time.
    There is only one way to have an object of an unknown type at compile time. That is to create the object's class at runtime using a classloader. Typically a URLClassloader.
    Look into
    Class.ForName(String)

  • How to cast vector to vector with out using loop. and how to override "operator =" of vector for this kind of condition.

    Hi All How to TypeCast in vector<>...  typedef  struct ...  to class... 
    //how to cast the vector to vector cast with out using loop
    // is there any way?
    //================ This is Type Definition for the class of ClsMytype=====================
    typedef struct tagClsMytype
    CString m_Name;
    int m_Index;
    double m_Value;
    } xClsMytype;
    //================ End of Type Definition for the class of ClsMytype=====================
    class ClsMytype : public CObject
    public:
    ClsMytype(); // Constructor
    virtual ~ClsMytype(); // Distructor
    ClsMytype(const ClsMytype &e);//Copy Constructor
    // =========================================
    DECLARE_SERIAL(ClsMytype)
    virtual void Serialize(CArchive& ar); /// Serialize
    ClsMytype& operator=( const ClsMytype &e); //= operator for class
    xClsMytype GetType(); // return the typedef struct of an object
    ClsMytype& operator=( const xClsMytype &e);// = operator to use typedef struct
    ClsMytype* operator->() { return this;};
    operator ClsMytype*() { return this; };
    //public veriable decleare
    public:
    CString m_Name;
    int m_Index;
    double m_Value;
    typedef struct tagClsMyTypeCollection
    vector <xClsMytype> m_t_Col;
    } xClsMyTypeCollection;
    class ClsMyTypeCollection : public CObject
    public:
    ClsMyTypeCollection(); // Constructor
    virtual ~ClsMyTypeCollection(); // Distructor
    ClsMyTypeCollection(const ClsMyTypeCollection &e);//Copy Constructor
    DECLARE_SERIAL(ClsMyTypeCollection)
    virtual void Serialize(CArchive& ar);
    xClsMyTypeCollection GetType();
    ClsMyTypeCollection& operator=( const xClsMyTypeCollection &e);
    ClsMyTypeCollection& operator=( const ClsMyTypeCollection &e); //= operator for class
    void Init(); // init all object
    CString ToString(); // to convert value to string for the display or message proposed
    ClsMyTypeCollection* operator->() { return this;}; // operator pointer to ->
    operator ClsMyTypeCollection*() {return this;};
    public:
    vector <ClsMytype> m_t_Col;
    //private veriable decleare
    private:
    //===================================================
    ClsMytype& ClsMytype::operator=( const xClsMytype &e )
    this->m_Name= e.m_Name;
    this->m_Index= e.m_Index;
    this->m_Value= e.m_Value;
    return (*this);
    //==========================Problem for the vector to vector cast
    ClsMyTypeCollection& ClsMyTypeCollection::operator=( const xClsMyTypeCollection &e )
    this->m_t_Col= (vector<ClsMytype>)e.m_t_Col; // how to cast
    return (*this);
    Thanks in Advance

    Hi Smirt
    You could do:
    ClsMyTypeCollection* operator->() {
    returnthis;};
    // operator pointer to ->
    operatorClsMyTypeCollection*()
    {returnthis;};
    public:
    vector<ClsMytype>
    m_t_Col;//??
    The last line with "vector<xClsMytype>
    m_t_Col;". It compiles but I doubt that is what you want.
    Regards
    Chong

  • How to cast an object in JSF?

    I am working on a travel application. A user can have several bookings and a booking can have several components. A component can be either air or hotel. I want to list the user's bookings on the client using JSF datatable.
    <h:dataTable var="component" value="#{booking.components}">
    Now depending upon the class of component I need to present different information.
    My question is how to cast the variable in JSF ?
    Thanks

    You can use the String value of Object#getClass()#getName() to lookup the classname and evaluate it in the 'rendered' attribute.
    Basic example:
    package mypackage;
    public class Animal {}
    package mypackage;
    public class Cat extends Animal {}
    package mypackage;
    public class Dog extends Animal {}
    package mypackage;
    public class Fish extends Animal {}MyBeanpublic List<Animal> getList() {
        List<Animal> animals = new ArrayList<Animal>();
        animals.add(new Dog());
        animals.add(new Cat());
        animals.add(new Fish());
        return animals;
    }JSF<h:dataTable value="#{myBean.list}" var="item">
        <h:column>
            <h:outputText value="It's a Cat" rendered="#{item.class.name == 'mypackage.Cat'}" />
            <h:outputText value="It's a Dog" rendered="#{item.class.name == 'mypackage.Dog'}" />
            <h:outputText value="It's a Fish" rendered="#{item.class.name == 'mypackage.Fish'}" />
        </h:column>
    </h:dataTable>As far there is no way to cast objects in JSF.
    Edit
    If you find it useful, move the classname request to the superclass:
    public class Animal {
        public String getType() {
            String className = getClass().getName();
            return className.substring(className.lastIndexOf('.') + 1);
    }Which makes life easier without struggling with package names:<h:outputText value="It's a Cat" rendered="#{item.type == 'Cat'}" />
    <h:outputText value="It's a Dog" rendered="#{item.type == 'Dog'}" />
    <h:outputText value="It's a Fish" rendered="#{item.type == 'Fish'}" />Message was edited by:
    BalusC

  • How to cast ArrayList to ....

    Hi,
    I got an ArrayList and its values are (1,2,3)
    List tempList = new ArrayList();
    tempList.add("1");
    tempList.add("2");
    tempList.add("3");
    I am wondering how to convert it to an int [] array.
    int [] tempInt;
    I know that I can do this : tempList.toArray
    but I don't know how to cast this to int[] type of array
    (note: not integet [] , just int[])
    Can anyone help? thanks a lot.

    Note: It would be much more efficient to use the wrapper classes for storing primitives in a Vector/ArrayList/LinkedList/... :
    tempList.add(new Integer(1));
    tempList.add(new Integer(2));
    tempList.add(new Integer(3));
    (getting the array as an int[] still requires a for-loop)

  • HOW TO  CAST NVARCHAR2 TO BLOB

    Hello
    i must stock my data to a nvarchar2 data (unicode) and i must also make full text search on this column, oracle does not support full text search on unicode data, so i have decided to stock my unicode data to a blob clomun, after i can create a full text index and search data.
    my problem is how to cast nvarchar2 to blob in oracle. i'm using a vb program with adodb to write and read data from the db and i must write the data (unicode text) in the blob column using the right cast which allows me to use directly adodb to read information (i have tried this with sql server with a varbinary(max) column and it works : i write a nvarchar data to the verbinary(max) column using the cast function, after, adodb can read directly the information without any explicit cast) is this possible on oracle
    thank you for your help

    What is your database character set? If it's AL32UTF8 you shouldn't really need to use NVARCHAR2 at all - you can store Unicode data in a VARCHAR2 or CLOB column.
    BLOB doesn't seem like the right datatype to use - if it's text you want to index then it should be in a VARCHAR2 or a CLOB column. If you put it in a BLOB then you'll have to explicity tell Oracle not to treat it as a binary document, and you will have to handle all character set issues manually.
    I'm afraid I know nothing about VB or ADODB.

  • How to cast object type to integer type?

    Hi,
    Object [] temp;
    Int [] value;
    How can I assign temp to value? (value = temp?)
    In other words how to cast array of type object to array of type integer?
    Thanks a lot.

    Hi,
    Object [] temp;
    Int [] value;
    How can I assign temp to value? (value = temp?)
    In other words how to cast array of type object to
    array of type integer?
    Thanks a lot.That my friend, is (sometimes) illegal. other times use
    value = (Integer[]) temp;
    Pray that temp is holding an Integer array so that you dont throw a runtime exception.
    I am assuming you know the diff between "int" and "Integer".

  • How to cast presentation variable

    Hi,
    How to cast the presentation variable in answers
    Thanks in advance
    naresh

    Hi Naresh,
    Have you tried to use the CAST function?
    CAST(@{test}{123} as char)
    With the above column Formula in Answers Request I can able to view the result 123, which is the default value specified the presentation variable 'test'.
    Hope this will helps you..
    -Vency

  • How to get BufferedImage of a JPanel

    Can anyone tell me : how to get BufferedImage of a JPanel

    I've done something like this:
    import java.awt.Graphics;
    import java.awt.LayoutManager;
    import java.awt.Dimension;
    import java.awt.image.BufferedImage;
    import java.io.InputStream;
    import java.io.FileInputStream;
    import javax.swing.JPanel;
    import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGImageDecoder;
    * @author Martin Breton
    public class JBackgroundImagePanel extends JPanel {
         private BufferedImage mImage = null;
         private InputStream mImageStream = null;
         public  String mImageFilename = null;
         public JBackgroundImagePanel( String ImageFilename ) {
              super();
              mImageFilename = ImageFilename;
              initialize();
         public JBackgroundImagePanel( BufferedImage ImageFilename ) {
              super();
              mImage = ImageFilename;
              initialize();
         public JBackgroundImagePanel( InputStream ImageStream ) {
              super();
              mImageStream= ImageStream;
              initialize();
         private  void initialize() {
              if(mImage == null)
                   try {
                        ClassLoader Loader = this.getClass().getClassLoader();
                        if( mImageStream == null )
                             mImageStream = Loader.getResourceAsStream(mImageFilename);
                             if( mImageStream == null )
                                 mImageStream = new FileInputStream( mImageFilename );     
                        JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder( mImageStream );
                        mImage = decoder.decodeAsBufferedImage();
                        mImageStream.close();
                   catch(Exception e){
                        System.out.print("Image could not be loaded in JBackgroundImagePanel.");
              this.setSize(mImage.getWidth(),mImage.getHeight());
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
              g.drawImage(mImage, 0, 0, null);
    }Hope this helps.
    proxi

  • How to cast a BLOB to OrdImage

    Hi,
    How can I cast or convert a BLOB to OrdImage? For example,
    <import...>
    public class ConvertBlobToOrdImage {
    public static void main(String args[]) throws Exception {
    // Load the Oracle JDBC driver:
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    // Connect to the database:
    Connection conn =
    DriverManager.getConnection(<"Your database connection">);
    conn.setAutoCommit(false);
    // Create a Statement:
    Statement stmt = conn.createStatement();
    String query = "SELECT blob FROM image_t where image_id = 1";
    OracleResultSet rset = (OracleResultSet) stmt.executeQuery(query);
    rset.next();
    OrdImage imageProxy = (OrdImage) rset.getCustomDatum(1, OrdImage.getFactory()); // <-- java.lang.ClassCastException: oracle.sql.BLOB
    rset.close();
    int height = imageProxy.getHeight();
    int width = imageProxy.getWidth();
    System.out.println("Image Dimension: " + height + " x " + width);
    System.out.println("Image Mime Type: " + imageProxy.getMimeType());
    TIA,
    Henry

    xwindy wrote:
    Does anyone knows how to cast a HashMap to HashMap<String, Object>?
    the session.getAttribute return only a HashMapthere is no way to do this safely
    you can use this annotation to suppress unchecked warnings
    @SuppressWarnings("unchecked")

  • Hql how to cast number to varchar2

    Hello.
    How to cast number to varchar2(to string)? I'm using hql toplink implementation and (don't know why) functions like cast(... as ...), to_char(...) and str(...) don't work. Please help me.
    Kuba :).
    Edited by: 854998 on 2011-04-27 03:12

    Hello Chris.
    First of all I'd like to thank you for answer. :)
    1)I can't use native query.
    2)What do you mean?
    3)I can't upgrade.
    I have something like this(it's only simple example, I have more complex query):
    getManager().createQuery("SELECT obj FROM " + EntityClass.class.getSimpleName() + " obj "
                        + " WHERE '14' = obj.number").getResultList();
    r.number is Number in Oracle and Long in entity class.
    I want to cast obj.number to String.
    Here: http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html#queryhql-expressions expressions like cast is valid.
    So, where's the problem? My toplink version is too old?
    Thanks a lot
    Kuba.

  • How to cast a column of a derived column in a view to NULL

    I have a derived column in my view and this column by default is picked up as not null.
    I want to cast it to null how can i do it ?
    Actual column
    column1 varchar(3) not null
    Expected column
    column1 varchar(3)  null
    Mudassar

    Shridar I  havent defined it but the derived column has been picked up as not null which is strange
    CREATE VIEW test
    AS
    SELECT 
    CASE
    WHEN COMPANY_SIZE IS NULL then  'a'
    ELSE 'b' 
    END AS
    column1 ----- added derived column identifier
    ,[Company_Size] AS [CompanySize]
    FROM xyz
    Mudassar

  • How to convert BufferedImage back to Image

    I have an Image from ImageIcon and i want to cut it using BufferedImage.getSubImage(...) and now from BufferedImage i want to turn it to Image again so that i can put in ImageIcon.
    Here is my code:
    URL img = new URL(location);
    ImageIcon imgIcon = new ImageIcon(img);
    Image image = imgIcon.getImage();
    //turn image into bufferedImage via graphic draw
    BufferedImage bi = new BufferedImage(..);
    Graphics g = bi.createGraphics();
    g.drawImage(image,0,0,null);
    bi.getSubImage(...);
    // how to turn bi back to Image newImage
    any ideas??

    More correctly, BufferedImage extends Image as Image is an abstract class and not an interface.
    Shaun

  • How to cast an object to a class known only at runtime

    I have a HashMap with key as a class name and value as the instance of that class. When I do a 'get' on it with the class name as the key, what I get back is a generic java.lang.Object. I want to cast this generic object to the class to which it belongs. But I don't know the class at compile time. It would be available only at runtime. And I need to invoke methods on the instance of this specifc class.
    I'm not aware of the ways to do it. Could anybody suggest/guide me how to do it? I would really appreciate.
    Thanks a lot in advance.

    Thanks all for the prompt replies. I am using
    reflection and so a generic object is fine, I guess.
    But a general question (curiosity) specific to your
    comment - extraordinarily generic...
    I understand there's definitely some overhead of
    reflection. So is it advisable to go for interface
    instead of reflection?
    Thanks.Arguments for interfaces rather than reflection...
    Major benefit at run-time:
    Invoking a method using reflection takes more than 20 times as long without using a JIT compiler (using the -Xint option of Java 1.3.0 on WinNT)... Unable to tell with the JIT compiler, since the method used for testing was simple enough to inline - which resulted in an unrealistic 100x speed difference.
    The above tests do not include the overhead of exception handling, nor for locating the method to be executed - ie, in both the simple method invocation and reflective method invocations, the exact method was known at compile time and so there is no "locative" logic in these timings.
    Major benefit at compile-time:
    Compile-time type safety! If you are looking for a method doSomething, and you typo it to doSoemthing, if you are using direct method invocation this will be identified at compile time. If you are using reflection, it will compile successfully and throw a MethodNotFoundException at run time.
    Similarly, direct method invocation offers compile-time checking of arguments, result types and expected exceptions, which all need to be dealt with at runtime if using reflection.
    Personal and professional recommendation:
    If there is any common theme to the objects you're storing in your hashtable, wrap that into an interface that defines a clear way to access expected functionality. This leaves implementations of the interface (The objects you will store in the hashtable) to map the interface methods to the required functionality implementation, in whatever manner they deem appropriate (Hopefully efficiently :-)
    If this is feasible, you will find it will produce a result that performs better and is more maintainable. If the interface is designed well, it should also be just as extensible as if you used reflection.

  • How to cast a fieldinput value to upper case.

    Im not a java programer I guess that this must be a silly thing.
    Im searching data in R/3 from 2 fields 1 numeric and the other alphanumeric. This alphanumeric fields if I put it in upper case works, if I wirte it in lower case doesnt works.
    In R/3 when I test the FM doesnt matter if I put it lower or upper case, it works fine.
    so I wanna know how can I in WD cast the value that I put in that fieldinput be converted to upper case when I hit the search button.
    Thx

    > Im not a java programer I guess that this must be a
    > silly thing.
    >
    > Im searching data in R/3 from 2 fields 1 numeric and
    > the other alphanumeric. This alphanumeric fields if I
    > put it in upper case works, if I wirte it in lower
    > case doesnt works.
    >
    > In R/3 when I test the FM doesnt matter if I put it
    > lower or upper case, it works fine.
    >
    > so I wanna know how can I in WD cast the value that I
    > put in that fieldinput be converted to upper case
    > when I hit the search button.
    >
    > Thx
    Hi,
    When you test the FM in SE37 in R3 there is an option at the top of the screen Called Uppercase/Lowercase - this controls whether the input is automatically converted to upper case for alphanumeric fields.
    The other option you have, if it is a custom FM, is to translate the input of the alphanumeric fields in the ABAP - it is quite common to have to translate or convert input data to make sure it is in the same format as the backend system.
    I prefer to do this sort of conversion on the backend system as usually you have a better guarentee that it will be in the correct format, than if you do it in the Java element.
    Just my opinion,
    Gareth.

Maybe you are looking for

  • Mac OS X version 10.5.8 - need an update to run iTunes 7

    I currently have a Mac OS X Version 10.5.8. I am unable to use my iPhone with iTunes, since it request version 7. I cannot download it, since my computer is outdated. What should i do? How can i get my computer up to date?

  • Massive quality loss when converting  a .mov file to an .avi or other

    I have been making short videos using final cut that look great in quicktime format. But when I convert them to any format that can be used in powerpoint or other window applications I am suffering a huge loss of quality. What am I doing wrong or how

  • Create a new HTML file by changing attributes

    Hello, I am going to add some attributes to create a new html file. Such as <div id="globalWrapper">becomes <div id="globalWrapper" style=...>I have completed partial task, but I have trouble on how to save it to a new file. Please look at my code. i

  • Problem with the adobe color picker

    Hi, recently I've noticed that my color picker has changed from this http://img78.imageshack.us/my.php?image=picture9iu7.png to this http://img368.imageshack.us/my.php?image=picture7en3.png I have been trying to reset the swatches and use other color

  • Lumia 1520 issue after cyan update

    After cyan update the screen start vibrating automatically and open Bing search and some random apps. I don't have any control of that. Then navigation bottom stop working. Sometimes I need to restart it or lock/unlock screen to make it work. This is