有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java翻转图像存储为字节[]数组

我有一个存储为byte[]数组的图像,我想在将其发送到其他地方处理(作为byte[]数组)之前翻转该图像

我四处搜索,如果不处理byte[]数组中的每一位,就找不到简单的解决方案

如何将字节数组[]转换为某种图像类型,使用现有的翻转方法翻转,然后将其转换回字节[]数组

有什么建议吗

干杯


共 (2) 个答案

  1. # 1 楼答案

    位图的字节数组:

    Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
    

    通过提供直角(180),使用此选项旋转图像:

    public Bitmap rotateImage(int angle, Bitmap bitmapSrc) {
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        return Bitmap.createBitmap(bitmapSrc, 0, 0, 
            bitmapSrc.getWidth(), bitmapSrc.getHeight(), matrix, true);
    }
    

    然后返回阵列:

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] flippedImageByteArray = stream.toByteArray();
    
  2. # 2 楼答案

    以下是用于翻转存储为字节数组的图像并以字节数组返回结果的方法

    private byte[] flipImage(byte[] data, int flip) {
        Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
        Matrix matrix = new Matrix();
        switch (flip){
            case 1: matrix.preScale(1.0f, -1.0f); break; //flip vertical
            case 2: matrix.preScale(-1.0f, 1.0f); break; //flip horizontal
            default: matrix.preScale(1.0f, 1.0f); //No flip
        }
    
        Bitmap bmp2 = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bmp2.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        return stream.toByteArray();
    }
    

    如果需要垂直翻转的图像,则将1传递为翻转值,将水平翻转传递为2

    例如:

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
       byte[] verticalFlippedImage = flipImage(data,1);
       byte[] horizontalFlippedImage = flipImage(data,2);
    }