首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ByteArrayOutputStream到FileBody

ByteArrayOutputStream到FileBody
EN

Stack Overflow用户
提问于 2011-10-20 07:40:37
回答 2查看 12.3K关注 0票数 7

我有一个Uri的图片,要么是采取或选择从画廊,我想加载和压缩为一个JPEG 75%的质量。我相信我已经做到了以下几点:

代码语言:javascript
复制
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Bitmap bm = BitmapFactory.decodeFile(imageUri.getPath());
bm.compress(CompressFormat.JPEG, 60, bos);

我并不是把它塞进一个名为ByteArrayOutputStreambos中,而是需要将它添加到MultipartEntity中,以便将其放到网站上。我想不出的是如何将ByteArrayOutputStream转换为FileBody.

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-10-20 09:10:48

使用ByteArrayBody代替(自HTTPClient 4.1以来可用),尽管它的名称也包含一个文件名:

代码语言:javascript
复制
ContentBody mimePart = new ByteArrayBody(bos.toByteArray(), "filename");

如果您使用的是HTTPClient 4.0,请使用InputStreamBody

代码语言:javascript
复制
InputStream in = new ByteArrayInputStream(bos.toByteArray());
ContentBody mimePart = new InputStreamBody(in, "filename") 

(这两个类都有接受附加MIME类型字符串的构造函数)

票数 14
EN

Stack Overflow用户

发布于 2012-12-18 12:50:51

我希望它能对某些人有所帮助,您可以在FileBody中将文件类型命名为"image/jpeg“,如下代码所示

代码语言:javascript
复制
HttpClient httpClient = new DefaultHttpClient();
            HttpPost postRequest = new HttpPost(
                    "url");
            MultipartEntity reqEntity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);
            reqEntity.addPart("name", new StringBody(name));
            reqEntity.addPart("password", new StringBody(pass));
File file=new File("/mnt/sdcard/4.jpg");
ContentBody cbFile = new FileBody(file, "image/jpeg");
reqEntity.addPart("file", cbFile);
    postRequest.setEntity(reqEntity);
            HttpResponse response = httpClient.execute(postRequest);
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(
                            response.getEntity().getContent(), "UTF-8"));
            String sResponse;
            StringBuilder s = new StringBuilder();
            while ((sResponse = reader.readLine()) != null) {
                s = s.append(sResponse);
            }

            Log.e("Response for POst", s.toString());

需要在项目中添加httpclient-4.2.2.jar、httpMIE-4.2.2.jar等jar文件。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7832598

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档