Android 将图像分成几 block 并获得等效大小的图像 block ( block )

标签 android bitmap bitmapimage android-bitmap

首先抱歉我的英语不好,我正在开发图像分割器应用程序并且已经完成,但现在的要求是当图像分割(分成几 block /chunks) 那么图像 block 的每一 block (chunk)都是50*50或40*40,最重要的是例如原始图像大小是420*320(它是动态的,我从图库中获取图像),然后将图像分割(划分)成 block ( block )后,图像大小仍与我上面提到的 420*320 相同,例如图像大小为 420* 320 和分割图像并将每个 block 大小划分为 50*50 后,剩余的 20 大小将分配给最后一个或任何 block ,所以我有 2 个问题:

注意:在我的应用程序中,我将图像放入图库中,然后分割图像并洗牌图像 fragment ( block ),然后合并图像,并创建一个** Canvas 用于绘制所有这些小( block )图像。**

  1. 分割420*320尺寸的图像后,需要图像 block (chunk)尺寸为50*50或40*40。
  2. 剩余的20*20 block ( block )分配给最后一个 block 或任何其他 block 。

这是分割前的原图,尺寸为420*320:

enter image description here

这是分割后的图像,整体图像尺寸相同420*320,但图像 block 大小为84*64,我想要 block 大小为50*50或40*40,整体图像尺寸也将是相同的420*320,剩余尺寸将分配给最后一个 block 。

enter image description here

这是我的 Activity :

package com.example.imagesplitter;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;


//public class ImageActivity extends Activity implements OnClickListener {
public class ImageActivity extends Activity {

    Button split_image;
    Button btnGallery;

    ImageView image;
    Uri selectedImage;
    private final int RESULT_LOAD_IMAGE = 1;
    int chunkNumbers = 25;
    ArrayList<Bitmap> chunkedImages;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);

     image = (ImageView) findViewById(R.id.source_image);



    alertDialogForCameraImage();

}

void pickImageFromGallery() {

    Intent pickPhoto = new Intent(Intent.ACTION_PICK,
               android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);                                                      
//      startActivityForResult(pickPhoto , 0); 
    startActivityForResult(pickPhoto, RESULT_LOAD_IMAGE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);


    switch(requestCode){

        case RESULT_LOAD_IMAGE:                
            if(resultCode==Activity.RESULT_OK) {
              //  takenPictureData = handleResultFromChooser(data);  

                 selectedImage = data.getData();
                String[] filePathColumn = {  MediaStore.Images.Media.DATA };

                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String picturePath = cursor.getString(columnIndex);
                cursor.close();

            //  ImageView imageView = (ImageView) findViewById(R.id.imgView);
                image.setImageBitmap(BitmapFactory.decodeFile(picturePath));

                // Function of split the image(divide the image into pieces)
                splitImage(image, chunkNumbers);
            }
            break;          
    }

    //And show the result in the image view when take picture from camera.

}


public void alertDialogForCameraImage() {
    AlertDialog.Builder adb = new AlertDialog.Builder(ImageActivity.this);
    adb.setTitle("Pick Image From Gallery: ");
    adb.setNegativeButton("Gallery", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {

            pickImageFromGallery();

      } });
    adb.show();
}



/**
 * Splits the source image and show them all into a grid in a new activity
 * 
 * @param image The source image to split
 * @param chunkNumbers The target number of small image chunks to be formed from the   source image
 */
private void splitImage(ImageView image, int chunkNumbers) {    

    //For the number of rows and columns of the grid to be displayed
    int rows,cols;

    //For height and width of the small image chunks 
    int chunkHeight,chunkWidth;

    //To store all the small image chunks in bitmap format in this list 
     chunkedImages = new ArrayList<Bitmap>(chunkNumbers);

    //Getting the scaled bitmap of the source image
    BitmapDrawable drawable = (BitmapDrawable) image.getDrawable();
    Bitmap bitmap = drawable.getBitmap();
    /*ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);*/
    Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), true);

    rows = cols = (int) Math.sqrt(chunkNumbers);
    chunkHeight = bitmap.getHeight()/rows;
    chunkWidth = bitmap.getWidth()/cols;
    /*chunkHeight = 300/rows;
    chunkWidth = 300/cols;*/

    //xCoord and yCoord are the pixel positions of the image chunks
    int yCoord = 0;
    for(int x=0; x<rows; x++){
        int xCoord = 0;
        for(int y=0; y<cols; y++){
            chunkedImages.add(Bitmap.createBitmap(scaledBitmap, xCoord, yCoord, chunkWidth, chunkHeight));
            xCoord += chunkWidth;
        }
        yCoord += chunkHeight;
    }

    // Function of merge the chunks images(after image divided in pieces then i can call this function to combine and merge the image as one)
    mergeImage(chunkedImages);


}

 void mergeImage(ArrayList<Bitmap> imageChunks) {

    Collections.shuffle(imageChunks);

    //Get the width and height of the smaller chunks
    int chunkWidth = imageChunks.get(0).getWidth();
    int chunkHeight = imageChunks.get(0).getHeight();

    //create a bitmap of a size which can hold the complete image after merging
    Bitmap bitmap = Bitmap.createBitmap(chunkWidth * 5, chunkHeight * 5,  Bitmap.Config.ARGB_4444);

    //create a canvas for drawing all those small images
    Canvas canvas = new Canvas(bitmap);
    int count = 0;
    for(int rows = 0; rows < 5; rows++){
        for(int cols = 0; cols < 5; cols++){
            canvas.drawBitmap(imageChunks.get(count), chunkWidth * cols, chunkHeight * rows, null);
            count++;
        }
    }

    /*
     * The result image is shown in a new Activity
     */

    Intent intent = new Intent(ImageActivity.this, MergedImage.class);
    intent.putExtra("merged_image", bitmap);
    startActivity(intent);
    finish();

}
}

这是我的图像分割方法:

private void splitImage(ImageView image, int chunkNumbers) {    

    //For the number of rows and columns of the grid to be displayed
    int rows,cols;

    //For height and width of the small image chunks 
    int chunkHeight,chunkWidth;

    //To store all the small image chunks in bitmap format in this list 
     chunkedImages = new ArrayList<Bitmap>(chunkNumbers);

    //Getting the scaled bitmap of the source image
    BitmapDrawable drawable = (BitmapDrawable) image.getDrawable();
    Bitmap bitmap = drawable.getBitmap();
    /*ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);*/
    Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), true);

    rows = cols = (int) Math.sqrt(chunkNumbers);
    chunkHeight = bitmap.getHeight()/rows;
    chunkWidth = bitmap.getWidth()/cols;
    /*chunkHeight = 300/rows;
    chunkWidth = 300/cols;*/

    //xCoord and yCoord are the pixel positions of the image chunks
    int yCoord = 0;
    for(int x=0; x<rows; x++){
        int xCoord = 0;
        for(int y=0; y<cols; y++){
            chunkedImages.add(Bitmap.createBitmap(scaledBitmap, xCoord, yCoord, chunkWidth, chunkHeight));
            xCoord += chunkWidth;
        }
        yCoord += chunkHeight;
    }


    mergeImage(chunkedImages);

}

任何帮助将不胜感激,非常感谢。

编辑:

enter image description here

更新: 这是示例图像,我想要这样的:

enter image description here

更新: 我认为应该是这样的:

enter image description here

最佳答案

据我了解该任务,如果原始图像大小为 420x320 并且 block 大小为 50x50,我们将有 7x5 50x50 block 、5 70x50 block (最后一列)、7 50x70 block (最后一行)和一个 70x70 block (右下角)。 然后在洗牌之后我们需要将它们放在一起。然而,如果我们只是随机合并 block ( picture 上的红叉),最有可能会发生冲突。

因此,在这种情况下,我随机确定大方形 block (70x70) 的位置 (X,Y),并将所有 70x50 block 放入 X 列,将所有 50x70 block 放入 Y 行。

可能还有其他一些情况:

  1. 如果原始图像大小为 200x180,那么我们将有 4x2 50x50 block 和 4 50x80 block 。然后我们对其进行洗牌,并应将一个较高的 block 放入一列以保留原始图像大小;
  2. 如果原始图像是 230x200,那么我们将有 3x4 50x50 block 和 4 80x50 block 。然后我们应该将一个更宽的 block 放入一行;
  3. 如果原始图像是 200x200,那么您的代码可以完美运行。

由于我们有不同大小的 block ,合并变得更加复杂 - 我们根据之前的 block 大小确定每个 block 的坐标。

package com.example.imagesplitter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {

Button split_image;
Button btnGallery;

ImageView sourceImage;
Uri selectedImage;
private final int RESULT_LOAD_IMAGE = 1;
int chunkSideLength = 50;

ArrayList<Bitmap> chunkedImage;

// Number of rows and columns in chunked image
int rows, cols;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);

    sourceImage = (ImageView) findViewById(R.id.source_image);

    alertDialogForCameraImage();
}

void pickImageFromGallery() {

    Intent pickPhoto = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    // startActivityForResult(pickPhoto , 0);
    startActivityForResult(pickPhoto, RESULT_LOAD_IMAGE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {

    case RESULT_LOAD_IMAGE:
        if (resultCode == Activity.RESULT_OK) {
            // takenPictureData = handleResultFromChooser(data);

            selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null,
                    null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            // ImageView imageView = (ImageView) findViewById(R.id.imgView);
            sourceImage.setImageBitmap(BitmapFactory.decodeFile(picturePath));

            // Function of split the image(divide the image into pieces)
            splitImage(sourceImage, chunkSideLength);
        }
        break;
    }

    // And show the result in the image view when take picture from camera.

}

public void alertDialogForCameraImage() {
    AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);
    adb.setTitle("Pick Image From Gallery: ");
    adb.setNegativeButton("Gallery", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {

            pickImageFromGallery();

        }
    });
    adb.show();
}

/**
 * Splits the source image and show them all into a grid in a new activity
 * 
 * @param image
 *            The source image to split
 * @param chunkSideLength
 *            Image parts side length
 */
private void splitImage(ImageView image, int chunkSideLength) {
    Random random = new Random(System.currentTimeMillis());

    // height and weight of higher|wider chunks if they would be
    int higherChunkSide, widerChunkSide;

    // Getting the scaled bitmap of the source image
    Bitmap bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();

    rows = bitmap.getHeight() / chunkSideLength;
    higherChunkSide = bitmap.getHeight() % chunkSideLength + chunkSideLength;

    cols = bitmap.getWidth() / chunkSideLength;
    widerChunkSide = bitmap.getWidth() % chunkSideLength + chunkSideLength;

    // To store all the small image chunks in bitmap format in this list
    chunkedImage = new ArrayList<Bitmap>(rows * cols);

    if (higherChunkSide != chunkSideLength) {
        if (widerChunkSide != chunkSideLength) {
            // picture has both higher and wider chunks plus one big square chunk

            ArrayList<Bitmap> widerChunks = new ArrayList<Bitmap>(rows - 1);
            ArrayList<Bitmap> higherChunks = new ArrayList<Bitmap>(cols - 1);
            Bitmap squareChunk;

            int yCoord = 0;
            for (int y = 0; y < rows - 1; ++y) {
                int xCoord = 0;
                for (int x = 0; x < cols - 1; ++x) {
                    chunkedImage.add(Bitmap.createBitmap(bitmap, xCoord, yCoord, chunkSideLength, chunkSideLength));
                    xCoord += chunkSideLength;
                }
                // add last chunk in a row to array of wider chunks
                widerChunks.add(Bitmap.createBitmap(bitmap, xCoord, yCoord, widerChunkSide, chunkSideLength));

                yCoord += chunkSideLength;
            }

            // add last row to array of higher chunks
            int xCoord = 0;
            for (int x = 0; x < cols - 1; ++x) {
                higherChunks.add(Bitmap.createBitmap(bitmap, xCoord, yCoord, chunkSideLength, higherChunkSide));
                xCoord += chunkSideLength;
            }

            //save bottom-right big square chunk 
            squareChunk = Bitmap.createBitmap(bitmap, xCoord, yCoord, widerChunkSide, higherChunkSide);

            //shuffle arrays
            Collections.shuffle(chunkedImage);
            Collections.shuffle(higherChunks);
            Collections.shuffle(widerChunks);

            //determine random position of big square chunk
            int bigChunkX = random.nextInt(cols);
            int bigChunkY = random.nextInt(rows);

            //add wider and higher chunks into resulting array of chunks
            //all wider(higher) chunks should be in one column(row) to avoid collisions between chunks
            //We must insert it row by row because they will displace each other from their columns otherwise
            for (int y = 0; y < rows - 1; ++y) {
                chunkedImage.add(cols * y + bigChunkX, widerChunks.get(y));
            }

            //And then we insert the whole row of higher chunks
            for (int x = 0; x < cols - 1; ++x) {
                chunkedImage.add(bigChunkY * cols + x, higherChunks.get(x));
            }

            chunkedImage.add(bigChunkY * cols + bigChunkX, squareChunk);
        } else {
            // picture has only number of higher chunks 

            ArrayList<Bitmap> higherChunks = new ArrayList<Bitmap>(cols);

            int yCoord = 0;
            for (int y = 0; y < rows - 1; ++y) {
                int xCoord = 0;
                for (int x = 0; x < cols; ++x) {
                    chunkedImage.add(Bitmap.createBitmap(bitmap, xCoord, yCoord, chunkSideLength, chunkSideLength));
                    xCoord += chunkSideLength;
                }
                yCoord += chunkSideLength;
            }

            // add last row to array of higher chunks
            int xCoord = 0;
            for (int x = 0; x < cols; ++x) {
                higherChunks.add(Bitmap.createBitmap(bitmap, xCoord, yCoord, chunkSideLength, higherChunkSide));
                xCoord += chunkSideLength;
            }

            //shuffle arrays
            Collections.shuffle(chunkedImage);
            Collections.shuffle(higherChunks);

            //add higher chunks into resulting array of chunks
            //Each higher chunk should be in his own column to preserve original image size
            //We must insert it row by row because they will displace each other from their columns otherwise
            List<Point> higherChunksPositions = new ArrayList<Point>(cols);
            for (int x = 0; x < cols; ++x) {
                higherChunksPositions.add(new Point(x, random.nextInt(rows)));
            }

            //sort positions of higher chunks. THe upper-left elements should be first 
            Collections.sort(higherChunksPositions, new Comparator<Point>() {
                @Override
                public int compare(Point lhs, Point rhs) {
                    if (lhs.y != rhs.y) {
                        return lhs.y < rhs.y ? -1 : 1;
                    } else if (lhs.x != rhs.x) {
                        return lhs.x < rhs.x ? -1 : 1;
                    }
                    return 0;
                }
            });

            for (int x = 0; x < cols; ++x) {
                Point currentCoord = higherChunksPositions.get(x);
                chunkedImage.add(currentCoord.y * cols + currentCoord.x, higherChunks.get(x));
            }

        }
    } else {
        if (widerChunkSide != chunkSideLength) {
            // picture has only number of wider chunks

            ArrayList<Bitmap> widerChunks = new ArrayList<Bitmap>(rows);

            int yCoord = 0;
            for (int y = 0; y < rows; ++y) {
                int xCoord = 0;
                for (int x = 0; x < cols - 1; ++x) {
                    chunkedImage.add(Bitmap.createBitmap(bitmap, xCoord, yCoord, chunkSideLength, chunkSideLength));
                    xCoord += chunkSideLength;
                }
                // add last chunk in a row to array of wider chunks
                widerChunks.add(Bitmap.createBitmap(bitmap, xCoord, yCoord, widerChunkSide, chunkSideLength));

                yCoord += chunkSideLength;
            }

            //shuffle arrays
            Collections.shuffle(chunkedImage);
            Collections.shuffle(widerChunks);

            //add wider chunks into resulting array of chunks
            //Each wider chunk should be in his own row to preserve original image size
            for (int y = 0; y < rows; ++y) {
                chunkedImage.add(cols * y + random.nextInt(cols), widerChunks.get(y));
            }

        } else {
            // picture perfectly splits into square chunks
            int yCoord = 0;
            for (int y = 0; y < rows; ++y) {
                int xCoord = 0;
                for (int x = 0; x < cols; ++x) {
                    chunkedImage.add(Bitmap.createBitmap(bitmap, xCoord, yCoord, chunkSideLength, chunkSideLength));
                    xCoord += chunkSideLength;
                }
                yCoord += chunkSideLength;
            }

            Collections.shuffle(chunkedImage);
        }
    }

    // Function of merge the chunks images(after image divided in pieces then i can call this function to combine
    // and merge the image as one)
    mergeImage(chunkedImage, bitmap.getWidth(), bitmap.getHeight());
}

void mergeImage(ArrayList<Bitmap> imageChunks, int width, int height) {

    // create a bitmap of a size which can hold the complete image after merging
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);

    // create a canvas for drawing all those small images
    Canvas canvas = new Canvas(bitmap);
    int count = 0;
    Bitmap currentChunk = imageChunks.get(0);

    //Array of previous row chunks bottom y coordinates 
    int[] yCoordinates = new int[cols];
    Arrays.fill(yCoordinates, 0);

    for (int y = 0; y < rows; ++y) {
        int xCoord = 0;
        for (int x = 0; x < cols; ++x) {
            currentChunk = imageChunks.get(count);
            canvas.drawBitmap(currentChunk, xCoord, yCoordinates[x], null);
            xCoord += currentChunk.getWidth();
            yCoordinates[x] += currentChunk.getHeight();
            count++;
        }
    }

    /*
     * The result image is shown in a new Activity
     */

    Intent intent = new Intent(MainActivity.this, MergedImage.class);
    intent.putExtra("merged_image", bitmap);
    startActivity(intent);
    finish();
}
}

抱歉我的英语不好:)

编辑:

如果你想得到原始图像,你需要注释掉所有的洗牌,并将大方 block 放在原来的位置:右下角

            //shuffle arrays
/*          Collections.shuffle(chunkedImage);
            Collections.shuffle(higherChunks);
            Collections.shuffle(widerChunks);
*/
            //determine random position of big square chunk
            int bigChunkX = cols - 1;
            int bigChunkY = rows - 1;

只有当图像宽度和高度都不能被 chunkSideLength 整除时,这才是正确的。 在其他情况下,您还应该注释改组并将更高/更宽的 block 放在原来的位置。禁用改组的 splitImage 函数的完整代码如下

    private void splitImage(ImageView image, int chunkSideLength) {
    Random random = new Random(System.currentTimeMillis());

    // height and weight of higher|wider chunks if they would be
    int higherChunkSide, widerChunkSide;

    // Getting the scaled bitmap of the source image
    Bitmap bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();

    rows = bitmap.getHeight() / chunkSideLength;
    higherChunkSide = bitmap.getHeight() % chunkSideLength + chunkSideLength;

    cols = bitmap.getWidth() / chunkSideLength;
    widerChunkSide = bitmap.getWidth() % chunkSideLength + chunkSideLength;

    // To store all the small image chunks in bitmap format in this list
    chunkedImage = new ArrayList<Bitmap>(rows * cols);

    if (higherChunkSide != chunkSideLength) {
        if (widerChunkSide != chunkSideLength) {
            // picture has both higher and wider chunks plus one big square chunk

            ArrayList<Bitmap> widerChunks = new ArrayList<Bitmap>(rows - 1);
            ArrayList<Bitmap> higherChunks = new ArrayList<Bitmap>(cols - 1);
            Bitmap squareChunk;

            int yCoord = 0;
            for (int y = 0; y < rows - 1; ++y) {
                int xCoord = 0;
                for (int x = 0; x < cols - 1; ++x) {
                    chunkedImage.add(Bitmap.createBitmap(bitmap, xCoord, yCoord, chunkSideLength, chunkSideLength));
                    xCoord += chunkSideLength;
                }
                // add last chunk in a row to array of wider chunks
                widerChunks.add(Bitmap.createBitmap(bitmap, xCoord, yCoord, widerChunkSide, chunkSideLength));

                yCoord += chunkSideLength;
            }

            // add last row to array of higher chunks
            int xCoord = 0;
            for (int x = 0; x < cols - 1; ++x) {
                higherChunks.add(Bitmap.createBitmap(bitmap, xCoord, yCoord, chunkSideLength, higherChunkSide));
                xCoord += chunkSideLength;
            }

            //save bottom-right big square chunk 
            squareChunk = Bitmap.createBitmap(bitmap, xCoord, yCoord, widerChunkSide, higherChunkSide);

            //shuffle arrays
/*          Collections.shuffle(chunkedImage);
            Collections.shuffle(higherChunks);
            Collections.shuffle(widerChunks);
*/
            //determine random position of big square chunk
            int bigChunkX = cols - 1;
            int bigChunkY = rows - 1;

            //add wider and higher chunks into resulting array of chunks
            //all wider(higher) chunks should be in one column(row) to avoid collisions between chunks
            //We must insert it row by row because they will displace each other from their columns otherwise
            for (int y = 0; y < rows - 1; ++y) {
                chunkedImage.add(cols * y + bigChunkX, widerChunks.get(y));
            }

            //And then we insert the whole row of higher chunks
            for (int x = 0; x < cols - 1; ++x) {
                chunkedImage.add(bigChunkY * cols + x, higherChunks.get(x));
            }

            chunkedImage.add(bigChunkY * cols + bigChunkX, squareChunk);
        } else {
            // picture has only number of higher chunks 

            ArrayList<Bitmap> higherChunks = new ArrayList<Bitmap>(cols);

            int yCoord = 0;
            for (int y = 0; y < rows - 1; ++y) {
                int xCoord = 0;
                for (int x = 0; x < cols; ++x) {
                    chunkedImage.add(Bitmap.createBitmap(bitmap, xCoord, yCoord, chunkSideLength, chunkSideLength));
                    xCoord += chunkSideLength;
                }
                yCoord += chunkSideLength;
            }

            // add last row to array of higher chunks
            int xCoord = 0;
            for (int x = 0; x < cols; ++x) {
                higherChunks.add(Bitmap.createBitmap(bitmap, xCoord, yCoord, chunkSideLength, higherChunkSide));
                xCoord += chunkSideLength;
            }

            //shuffle arrays
/*          Collections.shuffle(chunkedImage);
            Collections.shuffle(higherChunks);
*/
            //add higher chunks into resulting array of chunks
            //Each higher chunk should be in his own column to preserve original image size
            //We must insert it row by row because they will displace each other from their columns otherwise
            List<Point> higherChunksPositions = new ArrayList<Point>(cols);
            for (int x = 0; x < cols; ++x) {
                higherChunksPositions.add(new Point(x, rows - 1));
            }

            //sort positions of higher chunks. THe upper-left elements should be first 
            Collections.sort(higherChunksPositions, new Comparator<Point>() {
                @Override
                public int compare(Point lhs, Point rhs) {
                    if (lhs.y != rhs.y) {
                        return lhs.y < rhs.y ? -1 : 1;
                    } else if (lhs.x != rhs.x) {
                        return lhs.x < rhs.x ? -1 : 1;
                    }
                    return 0;
                }
            });

            for (int x = 0; x < cols; ++x) {
                Point currentCoord = higherChunksPositions.get(x);
                chunkedImage.add(currentCoord.y * cols + currentCoord.x, higherChunks.get(x));
            }

        }
    } else {
        if (widerChunkSide != chunkSideLength) {
            // picture has only number of wider chunks

            ArrayList<Bitmap> widerChunks = new ArrayList<Bitmap>(rows);

            int yCoord = 0;
            for (int y = 0; y < rows; ++y) {
                int xCoord = 0;
                for (int x = 0; x < cols - 1; ++x) {
                    chunkedImage.add(Bitmap.createBitmap(bitmap, xCoord, yCoord, chunkSideLength, chunkSideLength));
                    xCoord += chunkSideLength;
                }
                // add last chunk in a row to array of wider chunks
                widerChunks.add(Bitmap.createBitmap(bitmap, xCoord, yCoord, widerChunkSide, chunkSideLength));

                yCoord += chunkSideLength;
            }

            //shuffle arrays
/*          Collections.shuffle(chunkedImage);
            Collections.shuffle(widerChunks);
*/
            //add wider chunks into resulting array of chunks
            //Each wider chunk should be in his own row to preserve original image size
            for (int y = 0; y < rows; ++y) {
                chunkedImage.add(cols * y + cols - 1, widerChunks.get(y));
            }

        } else {
            // picture perfectly splits into square chunks
            int yCoord = 0;
            for (int y = 0; y < rows; ++y) {
                int xCoord = 0;
                for (int x = 0; x < cols; ++x) {
                    chunkedImage.add(Bitmap.createBitmap(bitmap, xCoord, yCoord, chunkSideLength, chunkSideLength));
                    xCoord += chunkSideLength;
                }
                yCoord += chunkSideLength;
            }

/*          Collections.shuffle(chunkedImage);
*/          }
    }

    // Function of merge the chunks images(after image divided in pieces then i can call this function to combine
    // and merge the image as one)
    mergeImage(chunkedImage, bitmap.getWidth(), bitmap.getHeight());
}

关于Android 将图像分成几 block 并获得等效大小的图像 block ( block ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24115066/

相关文章:

android - 我的 Android 应用存在内存问题

安卓 KitKat : android. view.InflateException : Error inflating class android. support.design.widget.NavigationView

Android TextView 可绘制,更改可绘制和文本之间的填充?

Android:位图内存不足

c# - Windows Phone - 字节数组到 BitmapImage 转换器抛出异常

Android BitmapFactory.Options.inSampleSize 导致应用程序崩溃

c# - 如何将 BitmapImage 转换为 Icon?

java - 如何将异步任务的输出设置为主 Activity 的 TextView

java - 如何在 SharedPreferences 中保存我的应用程序背景?

c# - EmguCV Out of memory exception in x86 release mode only-Sharpening Images