在上传之前调整图像大小(我的上传接受/选择是可以的)

时间:2014-08-20 04:10:46

标签: android upload resize

差不多两周后......我放弃了!!!

我实现了从图库和相机上传图像......

startActivityForResult... ok!  
EXTERNAL_CONTENT_URI... ok!  
ACTION_IMAGE_CAPTURE... ok!  
onActivityResult... ok!  
Activity.RESULT_OK ('cause I'm on Fragment)... ok!  
getActivity().getContentResolver().query()... ok!  
BitmapFactory.Options, opts.inSampleSize, .decodeFile... ok!  

但在使用...

上传到服务器之前,我无法将图像大小缩小到900px
- FileInputStream(sourceFile);  
- HttpURLConnection  
- DataOutputStream( getOutputStream)  
- dos.writeBytes(form... name... file name...)
- dos.write(buffer, 0, bufferSize) 

我无法理解......
- 在这种情况下如何使用“createScaledBitmap” - 如何在创建新位图时使用“writeBytes(... filename =?)”,它没有路径(至少我是这么认为的)。
- 如果我在磁盘上有原始图像,那么“createScaledBitmap”的结果路径是什么?
- 缓冲区如何工作(Step by Step会很棒),以及为什么在stackoverflow上的其他示例中不使用它?

我读过许多参考文献,包括:
http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
但我已经使用“options.inSampleSize”在我的片段上进行预览,我认为我需要(在我的情况下)“createScaledBitmap”来实现我的900x900px图像上传。

如果有另一种上传图片的方式,请调整大小...让我知道! (任何链接都会有所帮助)

我知道......我应该使用AsyncTask ......我正在努力! ;)

请考虑不要说技术,因为我学习Android的最糟糕的组合:新手和说西班牙语! xD

增加:
任何人都可以帮助@GVSharma在这里说的话吗? Upload compressed image

“你首先得到字符串路径na.so将其转换为位图并压缩它。而不是发送字符串文件路径作为该方法的第一个参数更改第一个参数到位图位图。或者你需要字符串文件路径然后再次转换将压缩的位图转换为String。希望这个可以帮助你“ (我不知道该怎么做)

public int uploadFile(String sourceFileUri) {

    final String fileName = sourceFileUri;

    HttpURLConnection conn = null;
    DataOutputStream dos = null; 
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(sourceFileUri);

    if (!sourceFile.isFile()) {
         ...
    } else {
        try {      
            // open a URL connection to the Servlet
             FileInputStream fileInputStream = new FileInputStream(sourceFile);
             URL url = new URL(upLoadServerUri);

             conn = (HttpURLConnection) url.openConnection();
             conn.setDoInput(true);
             conn.setDoOutput(true);
             conn.setUseCaches(false);
             conn.setRequestMethod("POST");
             conn.setRequestProperty("Connection", "Keep-Alive");
             conn.setRequestProperty("ENCTYPE", "multipart/form-data");
             conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
             conn.setRequestProperty("uploaded_file", fileName);//This is just for info?

             dos = new DataOutputStream(conn.getOutputStream());
             dos.writeBytes(twoHyphens + boundary + lineEnd);
             dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\"; filename=\""+fileName+"\"" + lineEnd);//How put in here a resized bitmap?
             dos.writeBytes(lineEnd);

             //Here I'm lost!
             bytesAvailable = fileInputStream.available();
             bufferSize = Math.min(bytesAvailable, maxBufferSize);
             buffer = new byte[bufferSize];

             bytesRead = fileInputStream.read(buffer, 0, bufferSize); 

             //I think...
             //this is a way to transfer the file in little pieces to server, right?, wrong?
             //If anybody can explain this, step by step... THANKS!!!
             while (bytesRead > 0) {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
              }
             dos.writeBytes(lineEnd);
             dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
             serverResponseCode = conn.getResponseCode();
             String serverResponseMessage = conn.getResponseMessage();
             Log.i("uploadFile", "Respuesta HTTP es: " + serverResponseMessage + ": " + serverResponseCode);

             if(serverResponseCode == 200){
                 ...               
             }
             fileInputStream.close();
             dos.flush();
             dos.close();
        } catch (MalformedURLException ex) {
            ...
        } catch (Exception e) { 
            ... 
        }

        dialog.dismiss();      
        return serverResponseCode;

    } // End else block
}//End uploadFile()

1 个答案:

答案 0 :(得分:3)

实际上有两种处理上述情况的方法,如下所述:

1]在服务器端(在您的网络服务中)进行一些安排,这样您就可以通过身高和身高。在服务器上传图像时的宽度,无论您传递的高度/宽度尺寸如何,都会缩小图像大小。这是第一个解决方案。

2]根据我的理解,如果您可以通过此代码减少位图维度:

try
{
int inWidth = 0;
int inHeight = 0;

InputStream in = new FileInputStream(pathOfInputImage);

// decode image size (decode metadata only, not the whole image)
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, options);
in.close();
in = null;

// save width and height
inWidth = options.outWidth;
inHeight = options.outHeight;

// decode full image pre-resized
in = new FileInputStream(pathOfInputImage);
options = new BitmapFactory.Options();
// calc rought re-size (this is no exact resize)
options.inSampleSize = Math.max(inWidth/dstWidth, inHeight/dstHeight);
// decode full image
Bitmap roughBitmap = BitmapFactory.decodeStream(in, null, options);

// calc exact destination size
Matrix m = new Matrix();
RectF inRect = new RectF(0, 0, roughBitmap.getWidth(), roughBitmap.getHeight());
RectF outRect = new RectF(0, 0, dstWidth, dstHeight);
m.setRectToRect(inRect, outRect, Matrix.ScaleToFit.CENTER);
float[] values = new float[9];
m.getValues(values);

// resize bitmap
Bitmap resizedBitmap = Bitmap.createScaledBitmap(roughBitmap, (int) (roughBitmap.getWidth() * values[0]), (int) (roughBitmap.getHeight() * values[4]), true);

// save image
try
{
    FileOutputStream out = new FileOutputStream(pathOfOutputImage);
    resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
}
catch (Exception e)
{
    Log.e("Image", e.getMessage(), e);
}
}
catch (IOException e)
{
   Log.e("Image", e.getMessage(), e);
}

完成上述编码步骤后,即可使用图像/位图上传逻辑/代码。