- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我是编程新手,我的任务之一是用 java 转换图像。这部分具体说“调用mirror会将图像从上到下反转。要从上到下反转,请将第一行交换为最后一行,将第二行交换为倒数第二行,依此类推,直到整个图像反转。”
这就是我目前拥有的,但每当我调用镜像时,它只是将图像转换为一堆无法区分的线条。我不知道如何解决这个问题!
public void mirror(){
int [][] imageData = data;
int i;
int j;
for (i=0; i < height; i++)
{
for(j=0; j < width; j++)
{
int temp = imageData[i][i-0];
imageData[i][i-0] = imageData[i-0][i];
imageData[i-0][i] = temp;
imageData[i][j] = temp;
}
}
}
我不应该修改的其他部分是并且已经给出了
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Scanner;
public class PictureLibrary {
// Maximum intensity
public static final int MAXVAL = 255;
// Image data
private int[][] image;
// Get image height
public int getHeight() {
return image.length;
}
// Get image width
public int getWidth() {
return image[0].length;
}
// Get image data
public int[][] getData() {
return image;
}
// Set image data
public void setData(int[][] data) {
image = data;
}
// Read PGM file
public void readPGM(String path) throws Exception {
int width;
int height;
int maxval;
try {
Scanner in = new Scanner(new File(path));
String magic = in.next();
if (!magic.equals("P2")) {
in.close();
throw new Exception("ERROR: cannot read .pgm file " + path);
}
width = in.nextInt();
height = in.nextInt();
maxval = in.nextInt();
image = new int[height][width];
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
image[y][x] = in.nextInt();
in.close();
} catch (IOException e) {
throw new Exception("ERROR: cannot read .pgm file " + path);
}
// Scale values to the range 0-MAXVAL
if (maxval != MAXVAL)
for (int j = 0; j < height; j++)
for (int i = 0; i < width; i++)
image[j][i] = (image[j][i] * MAXVAL) / maxval;
return;
}
// Write PGM file
public void writePGM(String path) throws Exception {
int height = getHeight();
int width = getWidth();
try {
PrintStream output = new PrintStream(new FileOutputStream(path));
output.println("P2");
output.println(width + " " + height);
output.println(MAXVAL);
for (int row = 0; row < height; row++)
for (int col = 0; col < width; col++)
output.println(image[row][col]); // One pixel per line!
output.close();
} catch (IOException e) {
throw new Exception("ERROR: cannot write .pgm file " + path);
}
}
}
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.swing.*;
public class ImageProgram extends JFrame implements ActionListener
{
private static final long serialVersionUID = 1L; // get rid of warning
// Program flags
private boolean mIsInitialized; // GUI initialized?
private boolean mIsDirty; // image modified?
// Menu items
private JMenuItem mOpenFile;
private JMenuItem mSaveFile;
private JMenuItem mExitCommand;
private JMenuItem mDecode;
private JMenuItem mSwap;
private JMenuItem mMirror;
private JMenuItem mExchange;
private JLabel mLabel;
// Transforms object from student
private ImageInterface mStudent;
// Array and static code are used to convert a gray scale to RGB
private static int[] pgm2RGB;
static {
pgm2RGB = new int[256];
for (int i = 0; i < 256; i++) {
pgm2RGB[i] = (255 << 24) | (i << 16) | (i << 8) | i;
}
}
// Constructor. Note that very little initialization is done here.
// Since a derived class may override some of the initialization methods
// these methods should NOT be called from a constructor because routines
// in the derived class could be executed before the constructor of the super
// class completes. In general, all code in the super class constructor
// should be executed before ANY code in the derived class is executed.
public ImageProgram () {
super();
setSize(new Dimension(400, 300));
}
// Satisfy the ActionListener interface. Most of the work is delegated to
// the method doAction(). This allows a derived class to override doAction
// (instead of actionPerformed()) and take advantage of the error handling
// done here. If a derived class overrides actionPerformed() in may need
// to duplicate the error handling.
public void actionPerformed (ActionEvent actionEvent) {
try {
doAction(actionEvent);
}
catch (Throwable t) {
t.printStackTrace();
}
}
// This can throw exceptions, because they are caught by performAction()
// If you derive your own class from this class, and add new menus
// or menu items, you would override this method to handle your new
// menu items and delegate the work back to this method if the "action"
// is not one of those you defined in your derived class. There are many
// ways to dispatch from an event to the underlying code. This illustrates
// one simple way of doing that.
protected void doAction (ActionEvent actionEvent) throws Exception {
Object src = actionEvent.getSource();
if (src == mOpenFile) openFile();
else if (src == mSaveFile) saveFile();
else if (src == mExitCommand) exitGUI();
else if (src == mDecode) decode();
else if (src == mSwap) swap();
else if (src == mMirror) mirror();
else if (src == mExchange) exchange();
}
// Override setVisible() to initialize everything the first time the
// component becomes visible
public void setVisible (boolean visible) {
if (visible) {
if (! mIsInitialized) {
startGUI();
mIsInitialized = true;
}
}
super.setVisible(visible);
}
// Build the GUI.
protected void startGUI() {
setJMenuBar(makeMenuBar());
addWindowListener(new WindowAdapter() {
public void windowClosing (WindowEvent we) {
mExitCommand.doClick(); // Press the Exit menu item
}
});
getContentPane().add(makeMainPanel());
}
// Exit the GUI
private void exitGUI() {
if (mIsDirty) {
if (!getYesNo("Data has not been saved.", "Continue?"))
return;
}
System.exit(0);
}
// Creates the main panel of the GUI
protected JPanel makeMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
mLabel = new JLabel();
panel.add(mLabel, BorderLayout.CENTER);
return panel;
}
// Created the menu bar for the GUI. Delegates most of the work to
// methods which create the individual menus. The "adds" should remind you
// of your work with ArrayLists. A JMenuBar is conceptually just a list of
// menus. You will find methods on a JMenuBar to manipulate the elements
// of the list.
protected JMenuBar makeMenuBar() {
JMenuBar mb = new JMenuBar();
mb.add(makeFileMenu());
mb.add(makeActionMenu());
return mb;
}
// Create the file menu. Again, the "adds" (see makeMeniItem)should remind you
// of list manipulation. A JMenu is conceptually a list of JMenuItems.
// Interestingly, a JMenu is a JMenuItem. Why do you think that is??
protected JMenu makeFileMenu() {
JMenu menu = makeMenu("File", 'F');
mOpenFile = makeMenuItem(menu, "Open...", 'O');
mSaveFile = makeMenuItem(menu, "Save...", 'S');
mExitCommand = makeMenuItem(menu, "Exit", 'X');
return menu;
}
// Create the action menu.
protected JMenu makeActionMenu() {
JMenu menu = makeMenu("Action", 'A');
mDecode = makeMenuItem(menu, "Decode" , 'D');
mSwap = makeMenuItem(menu, "Swap" , 'S');
mMirror = makeMenuItem(menu, "Mirror" , 'M');
mExchange = makeMenuItem(menu, "Exchange" , 'E');
return menu;
}
// Convenience method for making JMenu
protected JMenu makeMenu (String name, char mnemonic) {
JMenu menu = new JMenu(name);
menu.setMnemonic(mnemonic);
return menu;
}
// Convenience method for making JMenuItem
protected JMenuItem makeMenuItem (String name, char mnemonic) {
JMenuItem mi = new JMenuItem(name, (int) mnemonic);
mi.addActionListener(this);
return mi;
}
// Convenience method for putting JMenuItem in a menu
protected JMenuItem makeMenuItem (JMenu menu, String name, char mnemonic) {
JMenuItem mi = makeMenuItem(name, mnemonic);
menu.add(mi);
return mi;
}
// Convenience method to get yes/no from user
protected boolean getYesNo (String title, String message) {
int answer = JOptionPane.showInternalConfirmDialog(getContentPane(),
message,
title,
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
return (answer == JOptionPane.YES_OPTION);
}
// Open image file
private void openFile() throws Exception {
// Data saved?
if (mIsDirty) {
if (!getYesNo("Open file", "Data has not been saved. Continue?"))
return;
}
String fileName = selectFile("Select file to open", true);
if (fileName != null) {
mStudent = new Transforms();
mStudent.readImage(fileName);
resetImage();
mIsDirty = false;
}
}
// Save image file
private void saveFile() throws Exception {
String fileName = selectFile("Select file name to save", false);
if (fileName != null) {
mStudent.writeImage(fileName);
mIsDirty = false;
}
}
// Other student methods
private void decode() {
if (mStudent != null) {
mStudent.decode();
resetImage();
}
}
private void swap() {
if (mStudent != null) {
mStudent.swap();
resetImage();
}
}
private void mirror() {
if (mStudent != null) {
mStudent.mirror();
resetImage();
}
}
private void exchange() {
if (mStudent != null) {
mStudent.exchange();
resetImage();
}
}
// File selector
private String selectFile (String title, boolean open) {
String fileName = null;
JFileChooser jfc = new JFileChooser();
jfc.setCurrentDirectory(new File("."));
jfc.setDialogTitle(title);
int result;
if (open)
result = jfc.showOpenDialog(this);
else
result = jfc.showSaveDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File file = jfc.getSelectedFile();
fileName = file.getAbsolutePath();
}
return fileName;
}
// Reset image
private void resetImage() {
if (mStudent != null) {
// Copy the pixel values
int image[][] = mStudent.imageData();
int rows = image.length;
int cols = image[0].length;
BufferedImage buffer = new BufferedImage(cols, rows, BufferedImage.TYPE_INT_ARGB);
for (int row = 0; row < rows; row++) {
for (int col=0; col < cols; col++) {
int rgb = pgm2RGB[image[row][col]];
buffer.setRGB(col, row, rgb);
}
}
ImageIcon imageIcon = new ImageIcon(buffer);
mLabel.setIcon(imageIcon);
mIsDirty = true;
pack(); // make window just fit image
}
}
// Main program
public static void main (String[] args) throws IOException {
ImageProgram gui = new ImageProgram();
gui.setVisible(true);
}
}
public interface ImageInterface {
// Read the image
public void readImage(String inFile);
// Write the image
public void writeImage(String outFile);
// Get image data
public int[][] imageData();
// Decode the pixels
public void decode();
// Swap the nibbles in each pixel
public void swap();
// Mirror the image corner to corner
public void mirror();
// Exchange two rectangles in image
public void exchange();
}
最佳答案
我要做的是从顶部开始(并将其放在新数组的底部),而不是从图像的底部开始。我还将消除对临时矩阵的需要。
public void mirror(){
int [][] imageData = new int[height][width];
int i;
int j;
int x = 0;
for (i = height - 1; i = 0; i--)
{
for(j = 0; j < width; j++)
{
imageData[x][j] = data[i][j];
}
x++;
}
}
关于java - 交换二维数组行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42751601/
我在理解这些函数如何更新底层引用、原子等时遇到问题。 文档说:(应用当前身份值参数) (def one (atom 0)) (swap! one inc) ;; => 1 所以我想知道它是如何“扩展到
尝试让一段代码看起来更好。 我在 Clojurescript 中有以下内容: (swap! app-state assoc-in [:lastresults] []) (swap! app-state
我在数据库中有带有排序顺序号的记录。现在我想创建一个带有向上和向下按钮的用户界面来重新排序它们。制作两个 functionsUp(record) 和 functionDown(record) 的最佳算
如何才能让第二次点击时返回?我想我必须以某种方式找到活跃的,但不确定。 $("#test").click(function(){ $("#dsa").fadeOut() $("#asd
我需要有关这次考试的帮助。我需要反转输入字符串。 int main(void) { char str[30]; int strlen; int i=0; int count=0;int
我正在用 C 语言玩指针...我尝试编写一个接收指向值的指针、检索指针的指针并交换指向值的指针的交换,而不是接收指向值的指针和交换值的常规交换。 这是代码... 互换功能: void swap(voi
如何在 javascript 中切换值?例如,如果 x = apple,则函数应返回 x = orange。如果 x = orange,则函数应返回 x = apple。不确定,这里有什么用,切换或交
刚接触这类东西,可能做错了什么,但是- 我有 3 个成员 std::unique_ptr currentWeapon; std::unique_ptr weaponSlotOne; std::uniq
我想在 Map 内的不可变列表内交换项目,示例: const Map = Immutable.fromJS({ name:'lolo', ids:[3,4,5] }); 我正在尝试使用
我创建了动态数组。如果具有某些值,则填充。打印它。但是交换/交换指针后(任务是在特定条件下交换行) 条件取决于sumL。为了不浪费您的时间,我没有描述细节。 问题在于交换指针。 for ( k = 0
要反转整个 vector,存在 std::reverse。但我想将一个 vector “划分”为两部分(恰好在中间)并将两者反转,将它们放回一起并再次反转整个 vector 。例如我们有: 0 1 2
我正在致力于代码最小化和增强。我的问题是:是否可以在不破坏代码逻辑的情况下交换上面的 if 语句? int c1 = Integer.parseInt(args[0]) ; int c
我读过释放 vector 内存的最佳方法是: vector().swap(my_vector); 而且我真的不明白发生了什么。交换函数需要 2 个 vector 并交换它们的元素,例如: vector
我正在尝试编写一个 Haskell 函数,该函数接受一串字母对,并在所有字母组成的字符串中交换该对字母,但我想出的方法感觉很尴尬且不惯用。 我有 swap a b = map (\x-> if x =
我正在尝试使用向上和向下箭头交换两个元素。 JSFiddle 解决方案会很棒! 我的 HTML: Some text down Some ot
当将 subview 与另一个太阳 View 交换时,是否需要重新应用约束?是否需要删除适用于已删除 View 的约束? 或者它们应该自动持续存在? 最佳答案 约束是 View 的“一部分”。当您删除
所以我制作网站已经有一段时间了,但只是真正用于显示和信息的东西。我想尝试一下 AngularJs,所以我遵循了 Codeschool 上的指南。当我根据在线文档意识到我使用的语法不被推荐时,我在该应用
我正在尝试编写一个函数,可以将字符串中的 unicode 字符替换为非 unicode ASCII 字符,问题是上传包含它们的字符串时,unicode 连字符和引号不会被读取。 我希望该函数有一个带有
我目前正在使用 Azure 网站来部署我的应用程序。我目前正在使用两个网站,每个网站监听我的 GIT 的不同分支。如图所示here . 现在,为了让它变得完美,我只是缺少一种在这两个实例之间快速切换的
在我的 javascript 中,有两个包含一些值的 div。 我想交换这些div中的值。 有什么解决办法吗? 最佳答案 var temp = $('#div1').html(); $('#div1'
我是一名优秀的程序员,十分优秀!