Android:上传位图而不先将它们保存到文件系统

标签 android bitmap upload

我有两张图片,在内存中保存为位图:

private Bitmap image1;
private Bitmap image2;

现在我想将这些位图上传到我的服务器。这是我现在所做的: 我将我的图像以 PNG 格式写入文件系统(例如内部存储),使用 URI 作为位置。然后我调用此方法使用 multipart POST 上传文件:

private int uploadImageFiles(String image1Uri, String image2Uri) {
    File image1 = new File(image1Uri);
    File image2 = new File(image2Uri);

    try {
         HttpClient client = new DefaultHttpClient();
         HttpPost post = new HttpPost(uploadServerUriNodeJs);

         // additional headers for node.js server
         post.addHeader("ACCEPT", "application/melancholia+json");
         post.addHeader("ACCEPT-VERSION", "1.0");

         // user authorization
         String usernamePassword = USER + ":" + PASSWORD;
         String encodedUsernamePassword = Base64.encodeToString(usernamePassword.getBytes(), Base64.NO_WRAP);
         post.addHeader("AUTHORIZATION", "Basic " + encodedUsernamePassword);

         FileBody bin1 = new FileBody(image1, "image/png");
         FileBody bin2 = new FileBody(image2, "image/png");
         MultipartEntity reqEntity = new MultipartEntity();
         reqEntity.addPart("image1", bin1);
         reqEntity.addPart("image2", bin2);
         post.setEntity(reqEntity);
         HttpResponse response = client.execute(post);
         HttpEntity resEntity = response.getEntity();
         final String response_str = EntityUtils.toString(resEntity);
         if (resEntity != null) {
             return getIdFromResponse(response_str);
         }
    }
    catch (Exception ex){
         Log.e("Debug", "error: " + ex.getMessage(), ex);
    }
    return -1;
}

现在我的问题是:我不需要将这些位图写入我的应用程序的文件系统 - 除了上传。图像文件可能非常大,因此首先将它们写入文件系统可能会花费相当多的额外时间,这对性能不利。

我想要什么:有没有一种方法可以上传我的位图而不先将它们保存到文件系统?

顺便说一下,我不允许对服务器进行更改。


更新:这是我解决它的方法:

此示例使用的是 apache httpclient 4.3.6 在 http://hc.apache.org/downloads.cgi 获取 并查看这篇文章以了解要包含哪些库:Upload Photo using HttpPost MultiPartEntityBuilder 也不要忘记在“订购和导出”选项卡上检查它们

private String uploadImagesFromMemory(Bitmap img1, Bitmap img2) {

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    img1.compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] bin1 = stream.toByteArray();

    ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
    img2.compress(Bitmap.CompressFormat.PNG, 100, stream2);
    byte[] bin2 = stream2.toByteArray();

    try {
     HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(uploadServerUriNodeJs);

        // additional headers for node.js server
        post.addHeader("ACCEPT", "application/melancholia+json");
        post.addHeader("ACCEPT-VERSION", "1.0");

        // user authorization
        String usernamePassword = USER + ":" + PASSWORD;
        String encodedUsernamePassword = Base64.encodeToString(usernamePassword.getBytes(), Base64.NO_WRAP);
        post.addHeader("AUTHORIZATION", "Basic " + encodedUsernamePassword);

        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addBinaryBody("img1", bin1, ContentType.create("image/png"), "img1.png")
                .addBinaryBody("img2", bin2, ContentType.create("image/png"), "img2.png")
                .build();

        post.setEntity(reqEntity);
        Log.i("REQUEST", post.getRequestLine().toString());
        HttpResponse response = client.execute(post);
        HttpEntity resEntity = response.getEntity();
        final String response_str = EntityUtils.toString(resEntity);
        if (resEntity != null) {
            a.runOnUiThread(new Runnable(){
                   public void run() {
                        try {
                           Log.i("RESPONSE", "Response from server : " + response_str);
                       } catch (Exception e) {
                           e.printStackTrace();
                       }
                      }
               });
            return response_str;
        }
   }
   catch (Exception ex){
        Log.e("Debug", "error: " + ex.getMessage(), ex);
   }
   return "";
}

最佳答案

是的,您可以上传位图而不将它们保存到文件系统。写入 HttpURLConnection 返回的 OutputStream

private Bitmap bitmap;
HttpURLConnection connection;

    try
    {
        URL url = new URL("urlServer");
        connection = (HttpURLConnection) url.openConnection();

        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Content-Type", "multipart/form-data;");

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] byteArray = stream.toByteArray();
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(byteArray);
        outputStream.flush();
        outputStream.close();
    }
    catch (Exception ex)
    {
        //Exception handling
    }
    finally {
        if(connection != null) {
            connection.disconnect();
        }
    }

关于Android:上传位图而不先将它们保存到文件系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27369242/

相关文章:

android - 直接在android中裁剪YUV420/NV21字节数组

java - Robolectric 的阴影对象和模拟

php - 如何限制同时执行 PHP 脚本的人数? (队列, 'spot' 系统)

java - 上传文件到服务器,文件名为繁体中文

ios - 将图像上传到服务器( Objective-C )

android - 在 Fragment 中锁定屏幕时应用程序崩溃

android - 在Android的通知中将Drawable或Bitmap设置为图标

android - 在Android中以编程方式放大图片

c# - 在 C# 中读取 PPM 图像

c# - 在通过网络发送之前压缩位图