- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在捕获图像并将其保存到服务器路径中,它工作正常。捕获的图像看起来质量不错,但将图像保存到服务器后质量下降。
这是我的代码。
这是我的 Activity
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.VideoView;
public class PhotoIntentActivity extends Activity {
private static final int ACTION_TAKE_PHOTO_B = 1;
private Bitmap bitmap;
// private ProgressDialog dialog;
private static final String BITMAP_STORAGE_KEY = "viewbitmap";
private static final String IMAGEVIEW_VISIBILITY_STORAGE_KEY = "imageviewvisibility";
private ImageView mImageView;
private Bitmap mImageBitmap;
private static final String VIDEO_STORAGE_KEY = "viewvideo";
private static final String VIDEOVIEW_VISIBILITY_STORAGE_KEY = "videoviewvisibility";
private VideoView mVideoView;
private Uri mVideoUri;
private String mCurrentPhotoPath;
private File createImageFile() throws IOException {
File root = new File(Environment.getExternalStorageDirectory(), "Maya");
if (!root.exists()) {
root.mkdirs();
}
File file = new File(root, "android_" + System.currentTimeMillis()
+ ".JPEG");
return file;
}
private File setUpPhotoFile() throws IOException {
File f = createImageFile();
mCurrentPhotoPath = f.getAbsolutePath();
Log.d("onCreate", "Current file path is" + mCurrentPhotoPath);
return f;
}
private void setPic() {
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
int scaleFactor = 1;
if ((targetW > 0) || (targetH > 0)) {
scaleFactor = Math.min(photoW / targetW, photoH / targetH);
}
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
mImageView.setImageBitmap(bitmap);
mImageView.setVisibility(View.VISIBLE);
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(
"android.intent.action.MEDIA_SCANNER_SCAN_FILE");
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
private void dispatchTakePictureIntent(int actionCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
switch (actionCode) {
case ACTION_TAKE_PHOTO_B:
File f = null;
try {
f = setUpPhotoFile();
mCurrentPhotoPath = f.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(f));
} catch (IOException e) {
e.printStackTrace();
f = null;
mCurrentPhotoPath = null;
}
break;
default:
break;
} // switch
startActivityForResult(takePictureIntent, actionCode);
}
private void handleBigCameraPhoto() {
if (mCurrentPhotoPath != null) {
Log.d("onCreate", "inside the handleBigCameraPhoto");
new ImageUploadTask().execute(mCurrentPhotoPath);
setPic();
galleryAddPic();
mCurrentPhotoPath = null;
}
}
Button.OnClickListener mTakePicOnClickListener = new Button.OnClickListener() {
@Override
public void onClick(View v) {
dispatchTakePictureIntent(ACTION_TAKE_PHOTO_B);
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mImageView = (ImageView) findViewById(R.id.imageView1);
mImageBitmap = null;
mVideoUri = null;
Button picBtn = (Button) findViewById(R.id.btnIntend);
setBtnListenerOrDisable(picBtn, mTakePicOnClickListener,
MediaStore.ACTION_IMAGE_CAPTURE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTION_TAKE_PHOTO_B: {
if (resultCode == RESULT_OK) {
handleBigCameraPhoto();
}
break;
}
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putParcelable(BITMAP_STORAGE_KEY, mImageBitmap);
outState.putParcelable(VIDEO_STORAGE_KEY, mVideoUri);
outState.putBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY,
(mImageBitmap != null));
outState.putBoolean(VIDEOVIEW_VISIBILITY_STORAGE_KEY,
(mVideoUri != null));
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mImageBitmap = savedInstanceState.getParcelable(BITMAP_STORAGE_KEY);
mVideoUri = savedInstanceState.getParcelable(VIDEO_STORAGE_KEY);
mImageView.setImageBitmap(mImageBitmap);
mImageView
.setVisibility(savedInstanceState
.getBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY) ? ImageView.VISIBLE
: ImageView.INVISIBLE);
mVideoView.setVideoURI(mVideoUri);
mVideoView
.setVisibility(savedInstanceState
.getBoolean(VIDEOVIEW_VISIBILITY_STORAGE_KEY) ? ImageView.VISIBLE
: ImageView.INVISIBLE);
}
public static boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
private void setBtnListenerOrDisable(Button btn,
Button.OnClickListener onClickListener, String intentName) {
if (isIntentAvailable(this, intentName)) {
btn.setOnClickListener(onClickListener);
} else {
btn.setText(getText(R.string.cannot).toString() + " "
+ btn.getText());
btn.setClickable(false);
}
}
class ImageUploadTask extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
try {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(params[0], o);
final int REQUIRED_SIZE = 1024;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(params[0], o2);
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(
"http://192.168.1.113:9080/MavenWeb/ImageSaverServlet");
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
entity.addPart("uploaded", new ByteArrayBody(data,
"myImage.jpg"));
// entity.addPart("photoCaption","Maya's");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,
localContext);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse = reader.readLine();
return sResponse;
} catch (Exception e) {
return null;
}
}
@Override
protected void onPostExecute(String sResponse) {
try {
if (sResponse != null) {
JSONObject JResponse = new JSONObject(sResponse);
int success = JResponse.getInt("SUCCESS");
String message = JResponse.getString("MESSAGE");
if (success == 0) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Photo uploaded successfully",
Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
我的服务器端ImageSaverServlet是
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class ImageSaverServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if ( ServletFileUpload.isMultipartContent( request ))
{
List<FileItem> fileItems;
try {
fileItems = new ServletFileUpload( new DiskFileItemFactory( )).
parseRequest( request );
for ( FileItem item : fileItems )
{
String fieldName = item.getFieldName();
if ( item.isFormField())
{ item.getString() ;
}
else
{
try {
final BufferedImage bufferedImage = ImageIO.read(item.getInputStream());
File dir = new File("d:\\mayaImage");
dir.mkdir();
File imageFile = new File(dir+"\\newrose2.jpg");
ImageIO.write(bufferedImage, "jpg",imageFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
需要建议,为什么它会降低我的质量。
谢谢。
最佳答案
检查链接:
http://achorniy.wordpress.com/2010/04/26/howto-launch-android-camera-using-intents/
在这个例子中,调用了一个 Intent 来捕捉照片,并返回给你的 Activity ,有一个方法来获取文件对象引用,使用这个引用来获取
FileInputStream input=new FileInputStream(file);
使用以下方法从文件输入流中读取字节数组:
ByteArrayOutputStream baos=new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
while(input.read(buffer)!=-1)
{
baos.write(buffer);
}
baos.toByteArray();
关于android - 保存到服务器后图像质量下降。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9124567/
我正在尝试在特定图像上添加文本。它工作完美,但图像质量较低,尤其是 papyrus.ttf 字体。如何提高图像中文本的质量。但我需要高质量来打印输出。这是我的代码..它非常简单。 header("Co
是否可以获得现有图像的当前质量? 我想加载一个 JPEG 并在不改变质量和 DPI 的情况下再次保存它。 (我需要在保存前做一些像素操作) 最佳答案 JPEG 是一种有损格式。 这样做的直接方式,读取
我正在构建一个标签打印机。它由一个标志和一些文字组成,并不难。我已经花了 3 天时间尝试将原始 SVG Logo 绘制到屏幕上,但 SVG 太复杂,使用了太多渐变等。 所以我有一个高质量的位图 Log
我正在尝试以最快的方式以编程方式降低图像质量。现在,我能够从 byte[] 读取图像,然后作为 MemoryStream 将其读取到 Bitmap 并通过 Drawing。 Imaging.Encod
我允许用户上传图片。但是,我想保持 JPEG 质量不超过 90%。我打算做的是检测当前质量:- 如果少于 90% 什么都不做- 如果超过 90%,则使用 Image Magick 将图像重新压缩到 9
我正在制作一个 Android 应用程序,该应用程序通过使用内置摄像头作为 Intent 来使用摄像头。我正在逐个像素地对照片进行一些分析。我的 wildfire 在普通照片中返回 79000 像素,
我正在使用 python 程序生成一些数据,使用 matplotlib.pyplot 绘制数据,然后将图形显示在 latex 文件中。 我目前正在将图形保存为 .png 文件,但图像质量不是很好。我试
一直在尝试通过应用引擎将以下 png 文件上传到谷歌云存储: 在上传之前,我通过 PIL 运行它来处理任何图像旋转或背景颜色变化等 但是,即使在 python 命令行中运行相同的命令结果很好,但通过应
给定以下 Image 对象(它位于 ListView 对象的 DataTemplate 中): 我应该如何获得高质量的双三次插值图像? (在屏幕上,此图像的大小小于源 PNG,但默认调整大小似乎
如何在 PHP5 中压缩 GIF 图像文件? 我知道可以像这样处理 JPG imagejpeg($resource, $filename, $quality)根据 http://us.php.net/
我使用 html5 Canvas 元素在我的浏览器中调整图像大小。事实证明,质量非常低。我发现了这个:Disable Interpolation when Scaling a 但这无助于提高质量。 下
我正在使用 Visual Studio 2019 构建带有自定义任务 Pane 的 Excel 插件。 在用作自定义任务 Pane 的用户控件中,我添加了 imlNavigation (图片列表) 我
我是一名优秀的程序员,十分优秀!