如何直接从字节数组显示JPEG图像(在保存图像之前)?

4
我从客户端套接字接收一个jpeg图像(图像大小:50KB),并将其保存在模拟器SD卡中。然后我在ImageView中显示jpg图像。但是,我希望在保存图像到SD卡之前显示图像,因为我们的Android应用程序将从sockets接收连续的图像,如果我按照接收、保存和显示的方法,则会变得非常缓慢,所以为了增加速度,我想要直接从RAM中显示。为此,我需要将图像数组临时保存在RAM中。计划使用单独的线程来显示和保存。请指导我如何从字节数组中显示图像。
注意:我从socket接收JPEG图像,不是.bmp或.gif或.png。
以下是我从tcp socket接收图像的代码。(它正常工作) (注意:这是在单独的线程中完成的,请勿在UI线程中尝试。)
                    public byte[] mybytearray  = new byte[310000];
                    private int bytesRead=0;
                    private int current = 0;

                    ServerSocket serverSocket = new ServerSocket(SERVERPORT);  
                    Socket client = serverSocket.accept(); 


                   try {

                       myDir=new File("/mnt/sdcard/saved_images");

                        if (!myDir.exists()){
                            myDir.mkdir();
                        }else{
                            Log.d("ServerActivity","Folder Already created" );
                        }

                        String fpath = "/image0001.jpg";
                        File file = new File (myDir, fpath);
                        if (file.exists ()) file.delete ();


                        InputStream is = client.getInputStream();
                        FileOutputStream fos = new FileOutputStream(file);
                        BufferedOutputStream bos = new BufferedOutputStream(fos);
                        bytesRead = is.read(mybytearray,0,mybytearray.length);
                        current = bytesRead;

                 do {
                      bytesRead = is.read(mybytearray, current, (mybytearray.length-current));
                      if(bytesRead >= 0) current += bytesRead;

                 } while(bytesRead > -1);

                        bos.write(mybytearray, 0 , current);

                        Log.d("ServerActivity","Reconstructing Image from array");

                        bos.flush();
                        bos.close();
                        fos.flush();
                        fos.close();
                        is.close();
                        client.close();
                        serverSocket.close();
                    } catch (Exception e) { 
                  e.printStackTrace();
              }
3个回答

10

尝试将此代码片段插入您的代码中:

do {
    bytesRead = is.read(mybytearray, current, (mybytearray.length-current));
    if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);

ByteArrayInputStream inputStream = new ByteArrayInputStream(myByteArray);
bitmap = BitmapFactory.decodeStream(inputStream);
ImageView picture = new ImageView(this);
picture.setImageBitmap(bitmap);

bos.write(mybytearray, 0 , current);

5

使用位图,从字节数组创建它。

Bitmap bitmap;
bitmap= BitmapFactory.decodeByteArray(mybytearray, 0, mybytearray.length);

-1

将 byte[] 转换为位图。 请尝试以下操作

ByteArrayInputStream imageStream = new ByteArrayInputStream(byte[] array);
Bitmap bitmap = BitmapFactory.decodeStream(imageStream);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接