保存到服务器后,图像质量下降。 [英] Image quality decrease after saving to server.

查看:177
本文介绍了保存到服务器后,图像质量下降。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我捕捉图像,并保存到服务器的路径,其工作的罚款。拍摄的图像看起来不错的质量,但保存图像服务器质量下降后。

I am capturing an image ,and saving into server path, its working fine. Captured image looks good in quality but after saving image to server its quality decrease.

下面是我的code。

这是我的活动

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是

And My server side ImageSaverServlet is

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();
        }

    }
    }

}

需要的建议,为什么它减少我的质量。

Require Suggestion, why its decrease my quality.

感谢。

推荐答案

检查链接:

http://achorniy.word$p$pss.com/2010/04/26/howto-launch-android-camera-using-intents/

在这个例子中,一个意图被调用来拍摄照片,并返回到您的活动中,有一个方法来获得文件对象的引用,使用此引用来获得

In this sample, An intent is invoked to capture a photo, and returned back to your activity, there is a method to get File object reference, use this reference to get

FileInputStream input=new FileInputStream(file);

从的FileInputStream读取字节数组,使用:

read bytearray from the fileinputstream, by using:

ByteArrayOutputStream baos=new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
while(input.read(buffer)!=-1)
{
     baos.write(buffer);
}

baos.toByteArray();

这篇关于保存到服务器后,图像质量下降。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆