安卓上传图片到服务器(从相册和摄像机中选择图片)

8 篇文章 0 订阅
2 篇文章 0 订阅

1.因为图片较小,因此直接将图片转为base64字符,然后插入到数据库中

2.进入摄像机进行照片拍摄的代码为:

 //开启相机

           Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

           startActivityForResult(intent, 1);

3.进入相册选择照片拍摄的代码为:

  Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
           intent.setType("image/*");
           startActivityForResult(intent,2);

4.从onResultActivity方法中分别提取出图片:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            Log.d("errer", "canceled or other exception!");
            return;
        }
        if (requestCode == 1) {
            if(data!=null) {

                //获得压缩后的图片
                Bitmap bitmap =(Bitmap) data.getExtras().get("data");
                bitmap=getBitmap(bitmap);
                bitmap=ImageUtils.getZoomImage(bitmap,20.00);
                image=ImageUtils.bitToStr(bitmap);

                //将图片显示在图片控件中
                pub_pic.setImageBitmap(bitmap);

            }
        }
        if(requestCode==2){
            if(data!=null){
                   //获取图片定位符
                Uri uri = data.getData();
                try {
                    Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));

                          

                    bitmap=getBitmap(bitmap);
                    bitmap=ImageUtils.getZoomImage(bitmap,20.00);
                    image=ImageUtils.bitToStr(bitmap);

                    //将图片显示在图片控件中
                    pub_pic.setImageBitmap(bitmap);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

            }
        }
    }

5.上面用到的getBitMap(bitmap)方法是对图像进行压缩处理

 private   Bitmap getBitmap(Bitmap original) {
        Bitmap bitmap = null;
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            int picWidth = options.outWidth;
            int picHeight = options.outHeight;
            WindowManager windowManager = getWindowManager();
            Display display = windowManager.getDefaultDisplay();
            int screenWidth = display.getWidth();
            int screenHeight = display.getHeight();
            options.inSampleSize = 1;
            if (picWidth > picHeight) {
                if (picWidth > screenWidth)
                    options.inSampleSize = picWidth / screenWidth;
            } else {
                if (picHeight > screenHeight)
                    options.inSampleSize = picHeight / screenHeight;
            }
            options.inJustDecodeBounds = false;

            //创建输出流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            //将原图压缩成png
            original.compress(Bitmap.CompressFormat.PNG, 100, baos);
            //转换成inputstream
            InputStream isBm = new ByteArrayInputStream(baos.toByteArray());
            //进行压缩处理
            bitmap = BitmapFactory.decodeStream(isBm, null, options);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }

6.ImageUtils是个图片处理工具类,里面有各种静态方法

public class ImageUtils {
    //bitmap转为字符串
    public static String bitToStr(Bitmap bitmap){

        ByteArrayOutputStream baos = new ByteArrayOutputStream();// outputstream
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] appicon = baos.toByteArray();// 转为byte数组
        return Base64.encodeToString(appicon, Base64.DEFAULT);
    }
    //字符串转为bitmap
    public static Bitmap strToBit(String str){
        Bitmap bitmap = null;
        try
        {
            byte[] bitmapArray;
            bitmapArray = Base64.decode(str, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
            return bitmap;
        }
        catch (Exception e)
        {
            return null;
        }
    }

    /**
     * 图片的缩放方法
     *
     * @param bitmap  :源图片资源
     * @param maxSize :图片允许最大空间  单位:KB
     * @return
     */
    public static Bitmap getZoomImage(Bitmap bitmap, double maxSize) {
        if (null == bitmap) {
            return null;
        }
        if (bitmap.isRecycled()) {
            return null;
        }

        // 单位:从 Byte 换算成 KB
        double currentSize = bitmapToByteArray(bitmap, false).length / 1024;
        // 判断bitmap占用空间是否大于允许最大空间,如果大于则压缩,小于则不压缩
        while (currentSize > maxSize) {
            // 计算bitmap的大小是maxSize的多少倍
            double multiple = currentSize / maxSize;
            // 开始压缩:将宽带和高度压缩掉对应的平方根倍
            // 1.保持新的宽度和高度,与bitmap原来的宽高比率一致
            // 2.压缩后达到了最大大小对应的新bitmap,显示效果最好
            bitmap = getZoomImage(bitmap, bitmap.getWidth() / Math.sqrt(multiple), bitmap.getHeight() / Math.sqrt(multiple));
            currentSize = bitmapToByteArray(bitmap, false).length / 1024;
        }
        return bitmap;
    }

    /**
     * 图片的缩放方法
     *
     * @param orgBitmap :源图片资源
     * @param newWidth  :缩放后宽度
     * @param newHeight :缩放后高度
     * @return
     */
    public static Bitmap getZoomImage(Bitmap orgBitmap, double newWidth, double newHeight) {
        if (null == orgBitmap) {
            return null;
        }
        if (orgBitmap.isRecycled()) {
            return null;
        }
        if (newWidth <= 0 || newHeight <= 0) {
            return null;
        }

        // 获取图片的宽和高
        float width = orgBitmap.getWidth();
        float height = orgBitmap.getHeight();
        // 创建操作图片的matrix对象
        Matrix matrix = new Matrix();
        // 计算宽高缩放率
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(orgBitmap, 0, 0, (int) width, (int) height, matrix, true);
        return bitmap;
    }

    /**
     * bitmap转换成byte数组
     *
     * @param bitmap
     * @param needRecycle
     * @return
     */
    public static byte[] bitmapToByteArray(Bitmap bitmap, boolean needRecycle) {
        if (null == bitmap) {
            return null;
        }
        if (bitmap.isRecycled()) {
            return null;
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bitmap.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {

        }
        return result;
    }

}
7.以上便是安卓从手机的摄像机和相册中获得图片,并进行压缩处理,最后转为base64字符所用到的所有方法。





  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Android Studio,从相册选择图片可以通过以下步骤实现: 1. 在布局文件添加一个Button和一个ImageView,用于选择图片和展示图片。 2. 在Activity获取Button和ImageView的实例,并为Button设置点击事件。 3. 在点击事件,使用Intent调用系统相册,并在onActivityResult方法获取选择图片的Uri。 4. 将Uri转换为Bitmap,并设置到ImageView展示。 具体实现可以参考以下代码: 1. 在布局文件添加Button和ImageView: ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@+id/chooseLocalImage" android:text="点击选择本地照片" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <ImageView android:id="@+id/Image_message" android:layout_width="150dp" android:layout_height="150dp" /> </LinearLayout> ``` 2. 在Activity获取Button和ImageView的实例,并为Button设置点击事件: ``` public class MainActivity extends AppCompatActivity { private Button chooseLocalImage; private ImageView Image_message; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); chooseLocalImage = findViewById(R.id.chooseLocalImage); Image_message = findViewById(R.id.Image_message); chooseLocalImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent, 1); } }); } } ``` 3. 在onActivityResult方法获取选择图片的Uri,并将Uri转换为Bitmap: ``` @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1 && resultCode == RESULT_OK && data != null) { Uri uri = data.getData(); try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri); Image_message.setImageBitmap(bitmap); } catch (IOException e) { e.printStackTrace(); } } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值