Précédent   Forum des professionnels en informatique > Java > Général Java > Java & Mobiles > Java ME
Java ME Forum d'entraide Java Mobile Edition. Avant de poster -> FAQ Java ME, Cours Java ME
Partagez cette discussion sur d'autres réseaux sociaux : Viadeo Twitter Google Facebook Digg Delicious MySpace Yahoo
Réponse Proposer ce sujet en actualité
 
Outils de la discussion
Publicité
'
Vieux 18/10/2011, 12h32   #1
Candidat au titre de Membre du Club
 
Imene B
Inscription : mai 2010
Messages : 51
Détails du profil
Informations personnelles :
Nom : Imene B

Informations forums :
Inscription : mai 2010
Messages : 51
Points : 11
Points : 11
Par défaut Convertir un byte[] en image

Bonjour,

1) Je convertis ce que reçois en InputStream (des bits) en format String
Code :
1
2
3
                InputStream in = sc.openInputStream();
 
                String str = in.toString();
2) Je convertis ce String en un tableau de byte.
Code :
byte[] byt = str.getBytes();
3) Je cherche à convertir ce tableau de byte en image et l'afficher sur l'écran du téléphone.

Quelqu'un saurait-il m'expliquer comment faire ?

Merci d'avance pour votre aide.
b_imen est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 20/10/2011, 13h04   #2
Membre chevronné
 
Inscription : juin 2006
Messages : 444
Détails du profil
Informations personnelles :
Localisation : Allemagne

Informations forums :
Inscription : juin 2006
Messages : 444
Points : 680
Points : 680
Salut,

d'après la Javadoc, la classe Image a une floppée de fonctions statiques CreateImage dont une qui prend comme paramètre un tableau de byte :
Code :
createImage(byte[] imageData, int imageOffset, int imageLength)
Anikinisan est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 20/10/2011, 14h30   #3
Candidat au titre de Membre du Club
 
Imene B
Inscription : mai 2010
Messages : 51
Détails du profil
Informations personnelles :
Nom : Imene B

Informations forums :
Inscription : mai 2010
Messages : 51
Points : 11
Points : 11
Salut,
merci pour votre réponse;
Recherche faite, je trouve ce bout de code
Code :
1
2
3
ImageItem myImage = new ImageItem(null,Image.createImage(byt, 0, byt.length),ImageItem.LAYOUT_CENTER | ImageItem.LAYOUT_NEWLINE_BEFORE |ImageItem.LAYOUT_NEWLINE_AFTER,null);
 
form.append(myImage);
mais mon image ne s'affiche pas
???????
b_imen est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 20/10/2011, 16h29   #4
Membre chevronné
 
Inscription : juin 2006
Messages : 444
Détails du profil
Informations personnelles :
Localisation : Allemagne

Informations forums :
Inscription : juin 2006
Messages : 444
Points : 680
Points : 680
Est-ce qu'une exception est levée ?
Ton image est sous quel format (ils ne sont pas tous acceptés...) ?
Anikinisan est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 26/10/2011, 14h44   #5
Candidat au titre de Membre du Club
 
Imene B
Inscription : mai 2010
Messages : 51
Détails du profil
Informations personnelles :
Nom : Imene B

Informations forums :
Inscription : mai 2010
Messages : 51
Points : 11
Points : 11
aucune exception est levée
voila mon bout de code
Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
sc = (SocketConnection) Connector.open("socket://localhost:5555");
 
                System.out.println("ok!");
                form = new Form("Reception Datamatrix");
                form.append("DOWNLOAD EN COUR..........");
                InputStream in = sc.openInputStream();
                System.out.println("ok!!");
                String str=in.toString();
                byte[] byt=str.getBytes();
                System.out.println("ok!!!");
 
                ImageItem datamatrix = new ImageItem(null,Image.createImage(byt, 0, byt.length),ImageItem.LAYOUT_CENTER | ImageItem.LAYOUT_NEWLINE_BEFORE |ImageItem.LAYOUT_NEWLINE_AFTER,null);
                System.out.println("ok!!!!");
                form.append(datamatrix); 
 
                System.out.println("ok!!!!!");
dans l'output, voila ce que j'obtiens:
Citation:
ok!
ok!!
ok!!!
Execution completed.
je ne sais pas pourquoi le 4ième et 5ième ok ne s'affiche pas dans l'output
veuillez m'aider
est ce que le canvas intervient dans l'affichage
veuillez me clarifier ce point svp
merci
coté serveur:
Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
soc = ss.accept();
                jta.append("[" + new Date(DateFormat.LONG) + "]>Le client " + nbrclient + " : " + InetAddress.getLocalHost().getHostAddress() + " est connecté\n\n");
                in = new BufferedReader(new InputStreamReader(soc.getInputStream()));
                out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(soc.getOutputStream())),true);
 
                DataMatrix barcode = new DataMatrix(); 
                barcode.setData("DATA MATRIX"); 
                try {
 
                //barcode.renderBarcode("c:/barcode.gif");
                BufferedImage image = barcode.renderBarcode();
                //BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
                //image = ImageIO.read(new File("C://Documents and Settings/Administrateur.IMEN/Mes documents/NetBeansProjects/essai/src/essai/kid.jpg"));
                //JOptionPane.showMessageDialog(null, new ImageIcon(image), "", -1);
                int w = image.getWidth();
                int h = image.getHeight();
                System.out.println("width, height: " + w + ", " + h);
 
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(image, "JPEG", baos);
                StringBuilder sb = new StringBuilder();
                byte[] imageByteArray = baos.toByteArray();
                //for (int i=0; i<= imageByteArray.length; i++) System.out.println(imageByteArray[i]+"\t");
                for (byte by : imageByteArray)
                    sb.append(Integer.toBinaryString(by & 0xFF));System.out.println("ok!!!!!!!!!");
                    //System.out.println(sb.toString());
                    out.println(sb.toString()); 
                    out.flush(); System.out.println("ok!!");
                } catch (Exception ex) {System.out.println("erreur: "+ex.getMessage()); }
et dans l'output, voila ce que j'obtiens:
Citation:
width, height: 130, 130
ok!!!!!!!!!
ok!!
b_imen est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 26/10/2011, 15h09   #6
Membre chevronné
 
Inscription : juin 2006
Messages : 444
Détails du profil
Informations personnelles :
Localisation : Allemagne

Informations forums :
Inscription : juin 2006
Messages : 444
Points : 680
Points : 680
Tu as peut-être une erreur qui est captée a un niveau plus haut, comme tu n'as pas de try/catch dans ce bout de code.

Tu devrais rajouter une try/catch :
Code :
1
2
3
4
5
6
7
8
9
10
try
{
    ImageItem datamatrix = new ImageItem(null,Image.createImage(byt, 0, byt.length),ImageItem.LAYOUT_CENTER | ImageItem.LAYOUT_NEWLINE_BEFORE |ImageItem.LAYOUT_NEWLINE_AFTER,null);
    System.out.println("ok!!!!");
    form.append(datamatrix);
}
catch(Exception e)
{
    System.out.println(e.ToString());
}
(Ca fait longtemps que je n'ai plus fait de Java, et le try/catch est peut-être mal écrit. Merci de bien vouloir corriger, si nécessaire.)

Sinon, est-ce que dans tout tes try/catch tu affiches l'erreur dans la console ?
Si non, alors c'est mal et il faut l'afficher ! Autrement tu n'as pas de moyens de savoir si ça pète quelque part.
Anikinisan est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 26/10/2011, 15h56   #7
Candidat au titre de Membre du Club
 
Imene B
Inscription : mai 2010
Messages : 51
Détails du profil
Informations personnelles :
Nom : Imene B

Informations forums :
Inscription : mai 2010
Messages : 51
Points : 11
Points : 11
aucune exception ne se lève
j'ai mis le try catch
c ambigu
b_imen est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 26/10/2011, 16h35   #8
Membre chevronné
 
Inscription : juin 2006
Messages : 444
Détails du profil
Informations personnelles :
Localisation : Allemagne

Informations forums :
Inscription : juin 2006
Messages : 444
Points : 680
Points : 680

Tu as mis le try/catch et dans la fenêtre de sortie tu n'as toujours que les 3 premiers "Ok" ? C'est à devenir fou.
Et quand tu débugges ça donne quoi ?
Anikinisan est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 28/10/2011, 11h06   #9
Candidat au titre de Membre du Club
 
Imene B
Inscription : mai 2010
Messages : 51
Détails du profil
Informations personnelles :
Nom : Imene B

Informations forums :
Inscription : mai 2010
Messages : 51
Points : 11
Points : 11
Bonjour,
quant au débogage:
limage serveur affiche se qui se passe coté serveur
l'image client affiche se qui se passe coté client j2me
l'image emulateur affiche le resultat obtenu après exécution du client j2me. je vais vous expliquer le processus:
lorsque je me connecte au serveur et ce après saisie du login et du mot de passe, la phrase connxion en cours s'affiche (moi, je veux qu'elle s'affiche dans un nouveau form).
et la phrase image not available s'affiche lorsque je ferme le serveur.
voila mon bout de code coté client j2me:
Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package mobileApp;
 
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.SocketConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.ImageItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.*;
 
/**
 * @author amouna
 */
public class loginMidlet extends MIDlet implements CommandListener {
 
    private TextField name, password;
    private Form form, formI;
    private Command cmExit, cmLogin;
    private Display display;
    SocketConnection sc;
    Image img ;
 
    public loginMidlet() {
        name = new TextField("Login:", "", 10, TextField.ANY);
        password = new TextField("Password:", "", 10, TextField.PASSWORD);
        form = new Form("Sign in");
        cmExit = new Command("Cancel", Command.CANCEL, 2);
        cmLogin = new Command("Login", Command.OK, 2);
 
    }
 
    public void startApp() {
        display = Display.getDisplay(this);
        form.append(name);
        form.append(password);
        form.addCommand(cmExit);
        form.addCommand(cmLogin);
        form.setCommandListener(this);
        display.setCurrent(form);
 
    }
 
    public void pauseApp() {
    }
 
    public void destroyApp(boolean unconditional) {
        notifyDestroyed();
    }
 
    public void commandAction(Command c, Displayable d) {
 
        if (c == cmExit) {
            destroyApp(false);
            notifyDestroyed();
 
        } else if (c == cmLogin) {
 
            Alert alert;
            if (name.getString().equals("") || password.getString().equals("")) {
                alert = new Alert("Error", "You should enter ur name and password", null, AlertType.ERROR);
                alert.setTimeout(Alert.FOREVER);
                display.setCurrent(alert);
            } else {
                try {
                    MonThread t = new MonThread();
                    t.start();
                } catch (Exception x) {System.out.println("error: "+x.getMessage());
                }
            }
        }
    }
 
 
    class MonThread extends Thread {
        private Command exit;
 
        MonThread() {
 
        }
 
        public void run() {
 
            try {
                sc = (SocketConnection) Connector.open("socket://localhost:5555");
                form.append("connexion en cours...");
                InputStream in = sc.openDataInputStream();  
                Image myImage = Image.createImage(in);
 
                //ImageItem ii = new ImageItem(null, myImage, ImageItem.LAYOUT_DEFAULT, null);
                form.append(new ImageItem(null, myImage, ImageItem.LAYOUT_DEFAULT, null));
                form.addCommand(exit);
                display.setCurrent(form);
                //String str = in.toString();
                //byte[] byt=str.getBytes();
                /*try
                {
                //byte[] byt=str.getBytes();
                Image myImage = Image.createImage(byt, 0, byt.length);
                ImageItem ii = new ImageItem(null, myImage, ImageItem.LAYOUT_DEFAULT, null);
                if (formI.size() != 0)
                formI.set(0, ii);
                else
                formI.append(ii);
                formI.addCommand(exit);
                display.setCurrent(formI);
                } catch (Exception x) {
                System.out.println(x.getMessage());
                }*/
                }catch (IOException x) {
                    form.append("image not available");
                    System.out.println(x.getMessage());
                }
 
                }
 
 
    }
    }
les problèmes que j'ai:
Citation:
la réception de l'image
son affichage dans un nouveau form
quant au serveur:
Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
try {                
                soc = ss.accept();
                jta.append("[" + new Date(DateFormat.LONG) + "]>Le client " + nbrclient + " : " + InetAddress.getLocalHost().getHostAddress() + " est connecté\n\n");
                in = new BufferedReader(new InputStreamReader(soc.getInputStream()));
                out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(soc.getOutputStream())),true);
 
                DataMatrix barcode = new DataMatrix(); 
                barcode.setData("DATA MATRIX"); 
                try {
 
                //barcode.renderBarcode("c:/barcode.gif");
                BufferedImage image = barcode.renderBarcode();
                //BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
                //image = ImageIO.read(new File("C://Documents and Settings/Administrateur.IMEN/Mes documents/NetBeansProjects/essai/src/essai/kid.jpg"));
                //JOptionPane.showMessageDialog(null, new ImageIcon(image), "", -1);
                int w = image.getWidth();
                int h = image.getHeight();
                System.out.println("width, height: " + w + ", " + h);
 
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(image, "PNG", baos);
                StringBuilder sb = new StringBuilder();
                byte[] imageByteArray = baos.toByteArray();
                //for (int i=0; i<= imageByteArray.length; i++) System.out.println(imageByteArray[i]+"\t");
                for (byte by : imageByteArray)
                    sb.append(Integer.toBinaryString(by & 0xFF));System.out.println("ok!!!!!!!!!");
                    System.out.println(sb.toString());
                    out.println(sb.toString()); 
                    out.flush(); System.out.println("ok!!");
                } catch (Exception ex) {System.out.println("erreur: "+ex.getMessage()); }
veuillez m'aider
Merci
Images attachées
Type de fichier : png serveur.png (74,4 Ko, 3 affichages)
Type de fichier : png client.png (87,7 Ko, 1 affichages)
Type de fichier : png emulateur.png (85,8 Ko, 1 affichages)
b_imen est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 28/10/2011, 15h47   #10
Candidat au titre de Membre du Club
 
Imene B
Inscription : mai 2010
Messages : 51
Détails du profil
Informations personnelles :
Nom : Imene B

Informations forums :
Inscription : mai 2010
Messages : 51
Points : 11
Points : 11
salut,
veuillez m'aider

j'ai besoin au moins de connaitre comment afficher une image dans l’écran de l’émulateur.
j'ai foutue partout et aucun code m'a donner cette possibilité
je vous propose celui la et veuillez me le corriger
Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
 
import java.io.IOException;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.List;
import javax.microedition.midlet.MIDlet;
 
public class ImageMIDlet extends MIDlet implements CommandListener {
 
    // The MIDlet's Display object
    private Display display;
 
    // Flag indicating first call of startApp
    protected boolean started;
 
    // Exit command
    private Command exitCommand;
 
    // Back to examples list command
    private Command backCommand;
 
    // The example selection list
    private List examplesList;
 
    // The Canvases used to demonstrate different Items
    private Canvas[] canvases;
 
    // The example names. Used to populate the list.
    private String[] examples = {
        "DrawImage", "ImageGraphics"
    };
 
    protected void startApp() {
        if (!started) {
            started = true;
            display = Display.getDisplay(this);
 
            // Create the common commands
            createCommands();
 
            // Create the canvases
            createCanvases();
 
            // Create the list of examples
            createList();
 
            // Start with the List
            display.setCurrent(examplesList);
        }
    }
 
    protected void pauseApp() {
    }
 
    protected void destroyApp(boolean unconditional) {
    }
 
    public void commandAction(Command c, Displayable d) {
        if (d == examplesList) {
            // New example selected
            int index = examplesList.getSelectedIndex();
            display.setCurrent(canvases[index]);
        } else if (c == exitCommand) {
            // Exit. No need to call destroyApp
            // because it is empty.
            notifyDestroyed();
        } else if (c == backCommand) {
            // Go back to main selection list
            display.setCurrent(examplesList);
        }
    }
 
    private void createCommands() {
        exitCommand = new Command("Exit", Command.EXIT, 0);
        backCommand = new Command("Back", Command.BACK, 1);
    }
 
    private void createList() {
        examplesList = new List("Select Example", List.IMPLICIT);
        for (int i = 0; i < examples.length; i++) {
            examplesList.append(examples[i], null);
        } 
        examplesList.setCommandListener(this);
    }
 
    private void createCanvases() {
        canvases = new Canvas[examples.length];
        canvases[0] = createDrawImageCanvas();
//        canvases[1] = createImageGraphicsCanvas();
    }
 
    private void addCommands(Displayable d) {
        d.addCommand(exitCommand);
        d.addCommand(backCommand);
        d.setCommandListener(this);
    }
 
    // Create the Canvas for the image drawing example
    private Canvas createDrawImageCanvas() {
        Canvas canvas = new DrawImageCanvas();        
        addCommands(canvas);
        return canvas;
    } 
 
    // Create the Canvas to demonstrate drawing to an Image
    /*private Canvas createImageGraphicsCanvas() {
        Canvas canvas = new ImageGraphicsCanvas();        
        addCommands(canvas);
        return canvas;
    } */
}
 
// A canvas that illustrates image drawing
class DrawImageCanvas extends Canvas {
    static Image image;
 
    int count;
 
    public void paint(Graphics g) {
        int width = getWidth();
        int height = getHeight();
 
        // Fill the background using black
        g.setColor(0);
        g.fillRect(0, 0, width, height);
 
        // Load an image from the MIDlet resources
        if (image == null) {
            try {
                image = Image.createImage("/datamatrix.jpg");
            } catch (IOException ex) {
                g.setColor(0xffffff);
                g.drawString("Failed to load image!", 0, 0, Graphics.TOP | Graphics.LEFT);
                return;
            }
        }
 
        switch (count % 3) {
        case 0:
            // Draw the image at the top left of the screen
            g.drawImage(image, 0, 0, Graphics.TOP | Graphics.LEFT);
            break;
 
        case 1:
            // Draw it in the bottom right corner
            g.drawImage(image, width, height, Graphics.BOTTOM | Graphics.RIGHT);
            break;
        case 2:
            // Draw it in the center
            g.drawImage(image, width/2, height/2, Graphics.VCENTER | Graphics.HCENTER);
        }
        count++;
    }
}
/*
// A canvas that illustrates drawing on an Image
class ImageGraphicsCanvas extends Canvas {
 
    public void paint(Graphics g) {
        int width = getWidth();
        int height = getHeight();
 
        // Create an Image the same size as the
        // Canvas.
        Image image = Image.createImage(width, height);
        Graphics imageGraphics = image.getGraphics();
 
        // Fill the background of the image black
        imageGraphics.fillRect(0, 0, width, height);
 
        // Draw a pattern of lines
        int count = 10;
        int yIncrement = height/count;
        int xIncrement = width/count;
        for (int i = 0, x = xIncrement, y = 0; i < count; i++) {
            imageGraphics.setColor(0xC0 + ((128 + 10 * i) << 8) + ((128 + 10 * i) << 16));
            imageGraphics.drawLine(0, y, x, height);
            y += yIncrement;
            x += xIncrement;
        }
 
        // Add some text
        imageGraphics.setFont(Font.getFont(Font.FACE_PROPORTIONAL,
                                Font.STYLE_UNDERLINED, Font.SIZE_SMALL));
        imageGraphics.setColor(0xffff00);
        imageGraphics.drawString("Image Graphics", width/2, 0, Graphics.TOP | Graphics.HCENTER);
 
        // Copy the Image to the screen
        g.drawImage(image, 0, 0, Graphics.TOP | Graphics.LEFT);
    }
}*/
je me demande pourquoi on m'affiche
Citation:
failed to load image
l'image se trouve dans "le source package" qui contient les ressources de mon application
merci
b_imen est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 31/10/2011, 17h10   #11
Membre chevronné
 
Inscription : juin 2006
Messages : 444
Détails du profil
Informations personnelles :
Localisation : Allemagne

Informations forums :
Inscription : juin 2006
Messages : 444
Points : 680
Points : 680
Essaies sans le "/" au début
Code :
image = Image.createImage("datamatrix.jpg");
Anikinisan est déconnecté   Envoyer un message privé Réponse avec citation 00
Réponse Proposer ce sujet en actualité
Outils de la discussion



Fuseau horaire GMT +2. Il est actuellement 05h24.


 
 
 
 
Partenaires

Hébergement Web